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!
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 ]
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 ]