Skip to main content

can someone please explain java code to me

2 replies [Last post]
Joined: 2005-12-09

I'm not a new bie by any means, but I found a rather perculier java code that execute differently from one line to another.

with double value = 0.349575

double val1 = value * 100;
double val2 = Math.round(val1);
double val3 = val2/100;
this produces 0.35 in val3.

double val3 = Math.round(value * 100)/100;
this produces 0.0 in val3.

can someone please explain what the difference is? as the second one should evaluate in the same order as the first is setup.

Cheers for explanation anyone.


Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2007-04-17

Math.round returns a long and [url=]according to the spec[/url]: If this promoted type is int or long, then integer arithmetic is performed; if this promoted type is float or double, then floating-point arithmetic is performed.

So this work get the result you want:
[code]Math.round(value * 100)/100d[/code]

@Dmitriy: Math.round(value * 100) returns 35

Message was edited by: walterln

Joined: 2008-07-29

Because Math.round method return long value and expression Math.round(value * 100) = 0.

Correctly will double val4 = (double) Math.round(value * 100)/100;