Reputation: 5689
var_dump((float)'79.10')
returns me 79.09999999999999
. I've tried a million ways to try and round this value up to the original 79.10 as a float (number_format
, round
), and I can't find a way to do it.
Is there any way I can get a float
value of 79.10 from the original string?
Upvotes: 3
Views: 3147
Reputation: 882806
No, because 0.1
(and, by extension, 79.1
) is not actually representable as a float
(assuming IEEE-754 single or double precision encoding). 0.1
in that encoding has an infinitely recurring fractional part:
1001 1001 1001 1001 ...
You'll either have to leave it as a string or accept the fact that the encoding scheme does not have infinite precision and work around it.
An example of the latter is to only output the numbers to a certain precision, such as two decimal digits, and to make sure that (in-)equality comparisons use either absolute or relative deltas to compare numbers.
When you're adding numbers, it takes quite a few operations for the imprecision effects to become visible at the hundredths level. It's quicker when multiplying but still takes a while.
Upvotes: 7
Reputation: 5689
While paxdiablo is right and working with floats does not have infinite precision, I've discovered that it is indeed possible to represent 79.10 as a float by first adjusting PHP's precision setting:
ini_set('precision', 15);
After that, var_dump((float)'79.10')
correctly returns a float of 79.1
. The different results that everyone is seeing on their own machines seems to be a result of everyone having different precision values set by default.
Upvotes: 2
Reputation: 3529
This is impossible as a float
because it does not offer enough precision (see here for more information)
Now, in most languages you could cast it to a double
... Unfortunately, in PHP, float
and double
use exactly the same underlying datatype so in order to get the value you want, you would have to recompile PHP.
Your best option would be to use something like the PHP BCMath module for arbitrary precision.
Upvotes: 1