my dog learned polymorphism
The moose likes Beginning Java and the fly likes Floating point Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Floating point" Watch "Floating point" New topic

Floating point

Jess Ishasder

Joined: Feb 19, 2002
Posts: 21
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 ?
Thank you for your help!
Jorge Phillips
Ranch Hand

Joined: Jun 03, 2001
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:
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

Joined: Jan 30, 2002
Posts: 3451
Actually you could use the BigDecimal class to get the expected result which of course would involve quite a bit more work.

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
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 ]

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: Floating point
It's not a secret anymore!