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 ? Thank you for your help!
Jorge Phillips
Ranch Hand
Joined: Jun 03, 2001
Posts: 43
posted
0
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
Joined: Jan 30, 2002
Posts: 3451
posted
0
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
Sheriff
Joined: Dec 10, 2001
Posts: 7023
posted
0
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 ]