This also applies to
460, 920 and so on...
Is there any solution?
double in many languages). This representation has only finite precision (so not all numbers can be accurately represented) and it is binary, so values that seem to be easy to represent in decimal can turn out to be problematic to handle.
There is no fire-and-forget solution suitable for everyone. If you need an integer then simply round using
230/100*100 = (230 / 100) * 100 = 2.3 * 100 in binary
2.3 in binary is the recurring decimal:
This recurring decimal, cannot be accurately represented, due to limited precision, we get something like
Interestingly, if you chose a division operation like such that it was accurately representable (not a recurring decimal and all digits lying within the maximum significant digits accommodated by the FP standard) in binary, you wouldn't see any such discrepancy.
2.25 in binary is
Always be wary of precision when checking for equality between floating point values. Rounding up/down to a certain number of significant digits is good practice.
This problem relates to floating point inaccuracy. See this question for more details: Is floating point math broken?
For the same reason that if you were to be forced to stay to a certain precision, and to take every step, you'd give
Say the precision you had to keep to was 10 digits. After
10/3 you'd have
3.333333333. Then when you multiplied that by 3, you'd have
Now, since we know that the 3s will go on forever, we know that the 9s will go on forever, and so we know that the answer is really 10. But that's not the deal here, the deal is you apply each step as best you can, and then go on to the next.
As well as numbers that will result in recurring representations, there could be those that could be represented precisely, but not with the number of digits you are using.
10/3 cannot be represented perfectly in decimal, so
230/100 cannot be represented perfectly in binary.
2.3 or 2.4 can't be exactly represented in floating points. The difference is that the closest fp for 2.4 is 2.4000000953, while 2.3 is about 2.2999999523.
One can use
(x|0) converts x to integer, as the '|' operator forces the operands to integers. Even in this case 299.9943 is not rounded but truncated.
©2020 All rights reserved.