Generate random BigDecimal values ​​from a given range

I need to create a random BigDecimal value from a given range. How to do it in Java?

+5
source share
3 answers
class BigDecRand {
    public static void main(String[] args) {
        String range = args[0];
        BigDecimal max = new BigDecimal(range + ".0");
        BigDecimal randFromDouble = new BigDecimal(Math.random());
        BigDecimal actualRandomDec = randFromDouble.divide(max,BigDecimal.ROUND_DOWN);

        BigInteger actualRandom = actualRandomDec.toBigInteger();
    }
}
+5
source

I do like this

public static BigDecimal generateRandomBigDecimalFromRange(BigDecimal min, BigDecimal max) {
    BigDecimal randomBigDecimal = min.add(new BigDecimal(Math.random()).multiply(max.subtract(min)));
    return randomBigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP);
}

And how I run it:

BigDecimal random = Application.generateRandomBigDecimalFromRange(
    new BigDecimal(-1.21).setScale(2, BigDecimal.ROUND_HALF_UP),
    new BigDecimal(21.28).setScale(2, BigDecimal.ROUND_HALF_UP)
);
+3
source

BigInteger Java?

http://www.ponder2.net/doc/ponder2/net/ponder2/objects/P2Number.html

protected java.math.BigDecimal random()
Answer a random number depending upon the value of the receiver: 
0 => random long value
n => random integer >=0 and < n
n.m => random double >= 0.0 and < 1.0
Returns:
a random number
0

All Articles