如何使Math.random舍入到数字

时间:2015-03-23 23:24:48

标签: java random

我正在制作彩票型游戏,并使用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():)

5 个答案:

答案 0 :(得分:1)

编辑:误读原帖

您需要乘以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));

%.2fformat string

答案 1 :(得分:1)

你试过吗

Math.round(x)

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

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

Math.round(Math.random*100)

您将获得0到100之间的数字。

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

由于Math.random()返回0.0到1.0之间的双精度,你可以将结果乘以100.所以0.0 * 100 = 0,1.0 * 100 = 100,其间的所有内容都将在0到100之间

使用Math.round()获取完整的整数。因此,如果随机数是0.03454,则乘以100 = 3.454。绕过它得到3。

答案 4 :(得分:0)

正确:

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

不正确:

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

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

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