Melo Cool
Melo Cool

Reputation: 51

Converting from double to int with correct rounding

ok i have some thing like this:

int x = 5;  
int y = 3;  
int z = Math.round(x/y); 

and output ends up being 1 even though it should be 2, yes i have imported Math
I have tried stuff like:

int z = (int) ((x/y) + 0.5)  

but it doesn't work and continues being 1
I have also looked through this site for about half an hour and tried all the solutions that I found, some worked but when I changed x and y a little it rounded up instead of down.
x and y should actually be random numbers(that is the way it is in my actual program) but i have it simplified for this

Upvotes: 1

Views: 30

Answers (3)

caps lock
caps lock

Reputation: 511

Take a look at this :

    System.out.println("Math.round(5/3) " + Math.round(5 / 3));
    System.out.println("Math.round(5.0/3.0) " + Math.round(5.0 / 3.0));

output :

1
2

EDIT : so yes you need to cast at least one

Upvotes: 0

coder hacker
coder hacker

Reputation: 4868

It doesn't give 2, because you are doing integer arithmetic and so (5/3) will be 1 in integer arithmetic.

So my advice is to cast any one of operands.

Ex.

Math.round((double)x/y)

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

The problem is that by the time you pass a value to round() the "horse is already out of the barn: integer division chops off the fractional part, so Math.round() gets a clean 1, which it happily returns.

Casting x or y to double before the call will let you achieve the expected result:

int z = Math.round(((double)x)/y);  

Upvotes: 2

Related Questions