Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!

# Floating point

Jess Ishasder
Greenhorn
Posts: 21
Hi!
Suppose there are two floating point numbers:
float f1 = (float) 1000.43;
float f2 = (float) 1000.21;
float ans= f1 - f2;
Why ans is equal to 0.2199707, but not 0.22?
How can I perform subtraction on float/double ?

Jorge Phillips
Ranch Hand
Posts: 43
Internal float and double number representations and operations are not exact, and this is not a property of Java but of the way such numbers are internally represented in the hardware.
You do float and double arithmetic just as you do in your code, taking into account the fact above. Notice that if instead of float you use double as the type, your answer becomes much more exact, to wit:
1000.43
1000.21
0.2199999999999136
which for all practical purposes is 0.22!
So, if in float or double arithmetic you wanted to check two numbers are equal, you would check for their difference being an arbitrarily small quantity (say 10^-6) appropriate to the problem at hand.
[ February 27, 2002: Message edited by: Jorge Phillips ]

Michael Morris
Ranch Hand
Posts: 3451
Actually you could use the BigDecimal class to get the expected result which of course would involve quite a bit more work.

Dirk Schreckmann
Sheriff
Posts: 7023
Hello,
My two cents for this conversation...
If you want to format your decimal numbers any particular way, you might want to look at java.text.DecimalFormat. A quick search on JavaRanch produces links to previous conversations on this topic such as this one: DecimalFormat.
And here is some code to consider:

Note: The first logical test results in false and the second test results in true.
Good Luck,
-Dirk Schreckmann
[ March 05, 2002: Message edited by: Dirk Schreckmann ]