Generating random BigDecimal value from given range

帅比萌擦擦* 提交于 2019-11-29 10:54:49
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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!