get Random Float - Java java.lang

Java examples for java.lang:float

Description

get Random Float

Demo Code

// This program is free software: you can redistribute it and/or modify
//package com.java2s;
import java.util.Random;

public class Main {
    private static final Random randomNumberGenerator = new Random();

    public static float getRandomFloat(float minimumFloat,
            float maximumFloat, float precision) {
        if (minimumFloat > maximumFloat) {
            float temporaryHolder = maximumFloat;
            maximumFloat = minimumFloat;
            minimumFloat = temporaryHolder;
        }/*ww w. j  a  v a2 s  . c o m*/

        float range = maximumFloat - minimumFloat;
        float randomFloat = randomNumberGenerator.nextFloat() * range;
        float randomNumber = randomFloat + minimumFloat;

        float decimalShiftRight = randomNumber / precision;
        float roundedFloat = Math.round(decimalShiftRight);
        float decimalShiftLeft = roundedFloat * precision;

        return decimalShiftLeft;
    }
}

Related Tutorials