robbbbin
robbbbin

Reputation: 13

how to make Math.random round to a number

I am making a lottery type game and using Math.random() for the numbers. I want it to always print out what number you got in relation to 0 - 100 (so if Math.random outputted 0.03454 and the number to win was below 0.05, it would set the text of a label to 5). How would you make it round to just a 0.00 number? Here is some of the code if you want to see what I mean.

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);
}

I also have a button below that calls lotterymath() by the way :)

Upvotes: 1

Views: 14331

Answers (6)

user20616609
user20616609

Reputation: 1

When you create the variable multiply it by 100 like so:

double a = Math.random()*100;

then when you have to print it put an (int) before the variable just like down here:

System.out.print((int)a);

Upvotes: 0

Hender
Hender

Reputation: 400

correct:

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

INCORRECT:

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

you need to downcast to integer before assign to integer variable in order to don't get an error like this: error: incompatible types: possible lossy conversion from long to int

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

Upvotes: 0

Steven Manuel
Steven Manuel

Reputation: 1978

Since Math.random() returns a double between 0.0 to 1.0, you can just multiply the result with 100. So 0.0 * 100 = 0, 1.0 * 100 = 100, and everything in between will always be between 0 and 100.

Use Math.round() to get a full integer number. So if the random number is 0.03454, multiplied by 100 = 3.454. Round it to get 3.

Upvotes: 0

BevynQ
BevynQ

Reputation: 8269

I prefer to use BigDecimal when dealing with floating point numbers

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

Upvotes: 0

Targa
Targa

Reputation: 135

Have you tried

Math.round(x)

Checkout this link for the documentation: http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round(double)

EDIT: I might not have fully understanded your question, but I think if you use

Math.round(Math.random*100)

You'll get a number between 0 and 100.

Upvotes: 1

nanofarad
nanofarad

Reputation: 41281

Edit: misread original post:

You will want to multiply by 100, and then cast to an int to truncate it, or Math.round it instead:

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

or

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

Original:

Use String.format(String, Object...):

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

The %.2f is a format string.

Upvotes: 2

Related Questions