I need to generate random BigDecimal value from given range. How to do it in Java?
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();
}
}
I do this that way
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 the way 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)
);
Aravind R. Yarram
How to generate a random BigInteger value in Java?
From 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
来源:https://stackoverflow.com/questions/5023421/generating-random-bigdecimal-value-from-given-range