我需要从给定范围生成随机BigDecimal值。如何用Java做到这一点?
答案 0 :(得分:5)
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();
}
}
答案 1 :(得分:3)
我这样做
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);
}
我运行它的方式:
BigDecimal random = Application.generateRandomBigDecimalFromRange(
new BigDecimal(-1.21).setScale(2, BigDecimal.ROUND_HALF_UP),
new BigDecimal(21.28).setScale(2, BigDecimal.ROUND_HALF_UP)
);
答案 2 :(得分:-1)
How to generate a random BigInteger value in 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