How can I create a random BigDecimal in Java?

后端 未结 3 545
旧时难觅i
旧时难觅i 2021-01-05 17:19

This question: How to generate a random BigInteger describes a way to achieve the same semantics as Random.nextInt(int n) for BigIntegers.

I would like to do the sam

3条回答
  •  伪装坚强ぢ
    2021-01-05 17:40

    I might be missing the obvious here but how about creating two random BigIntegers, one being the integer part, and the other the fractional? Obviously the range of the "fractional" bigint would be dictated by the precision you want to allow, which you can't get away from pinning down.

    Update: This can be further simplified to work with just one random bigint. If you want a random number between 0 and n with k decimal precision (where k is a constant), you just generate a random number between 0 and n*10^k and divide it by 10^k.

提交回复
热议问题