programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Logical Error when executing (final result shows 2 instead of 3)

dan kom
Ranch Hand
Posts: 31
Hello, i wrote down the following program:

Now the problem is that  If i put in 47.63 as input  it gives me at the end 2 pennies instead of 3, even if i put \$_penny as Double, it gave me 2.99999... as result and not 3.0.  I wonder why it doesn't work because (47.63 % 0.05 = 0.03) and the calculation is done inside as double, so i wonder why it doesn't give me 3.0 and then int makes it a 3.

Paweł Baczyński
Bartender
Posts: 2083
44
• 1
47.63 % 0.05 = 0.029999999999999916
0.029999999999999916 / 0.01 = 2.9999999999999916
(int) 2.9999999999999916 = 2

You may want to convert the value to pennies before doing calculations (convert \$47.63 into 4763).
Alternatively, you may try using BigDecimal.

By the way, you should drop those \$_ from variable names.

Henry Wong
author
Sheriff
Posts: 23295
125
• 1
dan kom wrote:
Now the problem is that  If i put in 47.63 as input  it gives me at the end 2 pennies instead of 3, even if i put \$_penny as Double, it gave me 2.99999... as result and not 3.0.  I wonder why it doesn't work because (47.63 % 0.05 = 0.03) and the calculation is done inside as double, so i wonder why it doesn't give me 3.0 and then int makes it a 3.

Floating points are *not* precise. If you need a certain level of precision, then casting to int is generally not a good idea, as that simply truncates -- as you have noticed.

As for why such a simple expression is not precise while something more complex is more precise, keep in mind that the computer stores everything in binary. It is a binary number that is raised to the power of 2. And the exponent is also a binary number. So, what looks rational in decimal, may not be when it is stored by the computer.

Henry

Campbell Ritchie
Marshal
Posts: 56546
172
Henry Wong wrote:. . . As for why such a simple expression is not precise while something more complex is more precise, . . .
Don't you call that luck

In this case it just so happens that the imprecision was towards 2.9999999999... rather than towards 3.0000000000001... otherwise the error would never have been noticeable.

dan kom
Ranch Hand
Posts: 31
thanks

 Consider Paul's rocket mass heater.