I know that type conversion may lead small errors due to the way floating numbers are stored in binary. Yet I do have the use case of casting a float into a string, yet now I have the issue that this may remove a char:
$we_all_float_down_here = (float) 3467.60009765625;
$expected_string = '3467.60009765625';
var_dump($expected_string === (string) $we_all_float_down_here);
echo "Last chars gets stripped:n"
. (string) $we_all_float_down_here . "n"
. $expected_string;
This outputs:
bool(false)
Last chars gets stripped:
3467.6000976562
3467.60009765625
How can I cast the float to a string without losing any digit in the process?
Note:
ini_set('precision', 100);
won’t fix that certain float values are stored unprecislynumber_format
may work for some numbers just as my example, yet it too does not change the fact that other numbers will too be unprecise, or rather that some floats are identical to other different looking floats. (Similar how in decimal .99999… is identical to 1, even though it looks different, so are the floats3467.6000976563
and3467.60009765625318323146
identical for php.)
2
Answers
Don't use floats. Use string when precision is a requirement.
My confusion as to why I thought I was able to "get the float as is" stems from the fact that some floats may not be identical but their string representation is. Yet others floats are both identical in their float values and their string representation.
Given this code:
One gets the output:
This leads to the weird behavior that during a debug session one can see the specific correct float value of
3467.60009765625
, yet as soon as one casts their value to a string, the5
"disappears", as it string representation will always just be3467.6000976562
.Yet in the second case, both float representation mean exactly the same number, meaning
3467.60009765625318323146
will never be shown as for php, it IS identical to3467.6000976563
.See the code in action at: https://onlinephp.io/c/9a245
I believe you want to convert float to string instead of type-casting, in this case you may want to check this answer
Convert float to string in PHP