'Do arithmetic operations on FLOAT numbers correctly in PHP
I want the simplest thing to calculate:
$example = 90000000000009132 - 1;
echo sprintf('%.0f', $example);
Surprisingly I get:
90000000000009136
my question is - How can I get correct answer in php for such operation? Can you give me a correct code?
p.s. After searching the net, I've found explanations, saying that "this is not a bug" and some myths about float's and so on... Well, I won't start proving why I think that this really is an obvious bug and that we just don't care what happens in the background of PC, but the obvious thing is that we dont get correct number when subtracting X from Y, so it's definitely mistake! (But please, don't argue with me on this, because my question is different - clearly written above).
p.s.After being this question anomaly donwvoted, I couldn't find real solution in referred links. None of them worked, at least on my hosting. So, all most of those "answers" claimed to be the solution, seems useless on some hostings.
Solution 1:[1]
You can't.
The loss of precision when casting an integer to a float is caused by the way floats are stored in the FPU. This is basic computer science knowlegde and not an issue of PHP as a language. For more details on the subject please read https://en.wikipedia.org/wiki/IEEE_754.
However, the calculation itself works just fine for at least PHP 4.3+, according to 3v4l.org. The value you've used is an integer and well below PHP_INT_MAX. You can avoid type casting like this:
print $example . PHP_EOL;
print sprintf('%d', $example);
You can simlate the error of sprintf() by casting $example to float explicitly:
print (int) (float) $example; // incorrect
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Code4R7 |
