如何使 Math.random 舍入为数字

how to make Math.random round to a number

我正在制作彩票类型的游戏并使用 Math.random() 作为数字。我希望它总是打印出你得到的与 0 - 100 相关的数字(所以如果 Math.random 输出 0.03454 并且获胜的数字低于 0.05,它会将标签的文本设置为 5)。您如何将其四舍五入为 0.00 数字? 如果你想明白我的意思,这里有一些代码。

public void lotterymath()
{
    double x = Math.random();
    System.out.println(x);

    if (x <= 0.02)
        output.setText("you win  " + x);
    else
        output.setText( "you lost  " + x);
}

我下面还有一个按钮,顺便调用了 lotterymath():)

编辑:误读原文post:

您需要乘以 100,然后转换为 int 以截断它,或者转换为 Math.round

System.out.println(Math.round(x*100)); // rounds up or down

System.out.println((int) (x*100));

原文:

使用String.format(String, Object...):

System.out.println(String.format("%.2f", x));

%.2f是一个format string

你试过了吗

Math.round(x)

查看此 link 以获取文档:http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round(double)

编辑: 我可能没有完全理解你的问题,但我想如果你使用

Math.round(Math.random*100)

您会得到一个介于 0 和 100 之间的数字。

处理浮点数时我更喜欢使用 BigDecimal

BigDecimal myRounded = new BigDeicmal(Math.random()).setScale(2, BigDecimal.ROUND_HALF_UP);

由于 Math.random() returns 是 0.0 到 1.0 之间的双精度数,您只需将结果乘以 100。所以 0.0 * 100 = 0、1.0 * 100 = 100,以及between 将始终介于 0 和 100 之间。

使用Math.round() 得到一个完整的整数。所以如果随机数是0.03454,乘以100 = 3.454。四舍五入得到 3.

正确:

int var = (int)Math.round(Math.random()*100)

不正确:

int var = Math.round(Math.random()*100)

您需要在分配给整型变量之前向下转型为整型,以免出现如下错误: 错误:不兼容的类型:从 long 到 int 的可能有损转换

        int var = Math.round( Math.random() * 3);
                            ^