Java 你如何生成一个带小数位的随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4143304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:03:12  来源:igfitidea点击:

How do you generate a random number with decimal places

java

提问by user339108

I would like to generate random numbers between 1 & 10, with a decimal place of 1 
(e.g. 1.5, 9.4, 6.3, 2.9)

I would like to generate random numbers between 1 & 10, with 2 decimal places
(e.g. 1.51, 9.46, 6.32, 2.93)

I would like to generate random numbers between 1 & 10, with 3 decimal places

    (e.g. 1.512, 9.346, 6.329, 2.935)

One solution would be to have a random generator just for the decimal places and then concatenate with the number. Is there a simpler way to achieve this?

一种解决方案是为小数位设置一个随机生成器,然后与数字连接。有没有更简单的方法来实现这一目标?

采纳答案by Sean Patrick Floyd

Although BigDecimal solutions are more flexible, here's a simpler solution using int and double. This method takes a Randomobject, an upper and lower bound and a number of decimal places and returns an accordingly formatted string:

虽然 BigDecimal 解决方案更灵活,但这里有一个使用 int 和 double 的更简单的解决方案。此方法接受一个Random对象、一个上限和下限以及一些小数位,并返回一个相应格式的字符串:

/**
 * Generate a decimal string representation of a random number within the
 * supplied bounds.
 * 
 * @param random
 *            the random object (if null, a new one will be created)
 * @param lowerBound
 *            the lower bound, inclusive
 * @param upperBound
 *            the upper bound, inclusive
 * @param decimalPlaces
 *            the decimal places of the result
 * @return the formatted string
 */
public static String getRandomValue(final Random random,
    final int lowerBound,
    final int upperBound,
    final int decimalPlaces){

    if(lowerBound < 0 || upperBound <= lowerBound || decimalPlaces < 0){
        throw new IllegalArgumentException("Put error message here");
    }

    final double dbl =
        ((random == null ? new Random() : random).nextDouble() //
            * (upperBound - lowerBound))
            + lowerBound;
    return String.format("%." + decimalPlaces + "f", dbl);

}

Test Code:

测试代码:

final Random rnd = new Random();

for(int decpl = 0; decpl < 3; decpl++){
    for(int low = 0; low < 2; low++){
        for(int high = low + 1; high < low + 3; high++){
            System.out.println("Random Value between " + low + " and "
                + high + " with " + decpl + " decimal places:");
            System.out.println(getRandomValue(rnd, low, high, decpl));
        }
    }
}

Output:

输出:

Random Value between 0 and 1 with 0 decimal places:
0
Random Value between 0 and 2 with 0 decimal places:
1
Random Value between 1 and 2 with 0 decimal places:
1
Random Value between 1 and 3 with 0 decimal places:
3
Random Value between 0 and 1 with 1 decimal places:
0.6
Random Value between 0 and 2 with 1 decimal places:
1.5
Random Value between 1 and 2 with 1 decimal places:
1.1
Random Value between 1 and 3 with 1 decimal places:
1.9
Random Value between 0 and 1 with 2 decimal places:
0.52
Random Value between 0 and 2 with 2 decimal places:
0.82
Random Value between 1 and 2 with 2 decimal places:
1.75
Random Value between 1 and 3 with 2 decimal places:
1.10

回答by Jigar Joshi

Generate a double and than format according to your decimal need

根据您的十进制需要生成双精度和比格式

回答by Jon Skeet

Well one obvious suggestion is to generate a single integer and divide it appropriately. So for 3DPs, you'd generate a number between 1000 and 9999 (or 10000, depending on the exact bound you wanted) and then divide it by 10000.

一个明显的建议是生成一个整数并适当地划分它。因此,对于 3DP,您将生成 1000 到 9999(或 10000,取决于您想要的确切界限)之间的数字,然后将其除以 10000。

I suggest you use BigDecimalin the actual division, to maintain the decimals exactly.

我建议您BigDecimal在实际除法中使用,以精确保持小数。

回答by christian

1)
(int) ((Math.random() * 90) + 10) / 10.0
2)
(int) ((Math.random() * 900) + 100) / 100.0
3)
(int) ((Math.random() * 9000) + 1000) / 1000.0

1)
(int) ((Math.random() * 90) + 10) / 10.0
2)
(int) ((Math.random() * 900) + 100) / 100.0
3)
(int) ((Math.random() * 9000) + 1000) / 1000.0