Unexpected Java Compute Result

Why the following code:

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

displays the result "1998"?

+4
source share
6 answers

Rounding errors. If you look at the result of your calculations without a cast, you will get:

 1998.9999999999998 

So, when you throw an int, the decimal part is discarded, not rounded, and you get 1998.

Moral - if you need an exact answer, do not use float / double at all. If you're talking about a discrete value like money, use int and process the atomic unit (like pence.) If you need exact decimal numbers, then BigDecimal is your friend.

While you can use the result here, using Math.round() to bring the result to where it was expected, this will not work in all cases and will not be able to fix the underlying problem.

+9
source

This is because 19.99 is impossible to imagine for sure.

 System.out.println(new BigDecimal(19.99)); 

prints the value that it actually represents, which is the closest to 19.99 that it can represent.

 19.989999999999998436805981327779591083526611328125 

and 19.99 * 100 is

 System.out.println(new BigDecimal(19.99 * 100)); 

which the

 1998.999999999999772626324556767940521240234375 

The problem is that you have a presentation error in 19.99 that still exists when multiplied by 100, you get a number that is a little too small.

if you multiply by 100 and round up , which means (int) , you should expect to get 1998.

Alternative is

 System.out.println(Math.round(19.99 * 100)); 
+5
source

because calculating 19.99 * 100 will result in 1998.999999, and you drop it to int, it will drop the fractional part.

+1
source

This is due to rounding issues. double and float are prone to these problems, so it is recommended that you use the BigDecimal class.

This code should print the expected:

 BigDecimal bg = new BigDecimal("19.99"); System.out.println(bg.multiply(new BigDecimal("10"))); 

This gives:

199.90

+1
source
 System.out.println((19.99 * 100)); 

prints the result 1998.9999999999998, adding an int , while it truncates part of the share and returns 1998

+1
source

Floating-point data types (float and double in Java) can roughly represent decimal values. For more information, see Joshua Bloch 's words on wisdom on this subject.

+1
source

All Articles