Convert float to string in php?
67,354
Solution 1
echo number_format($float,0,'.','');
note: this is for integers, increase 0 for extra fractional digits
Solution 2
$float = 0.123;
$string = sprintf("%.3f", $float); // $string = "0.123";
Solution 3
It turns out json_decode
by default casts large integers as floats. This option can be overwritten in the function call:
$json_array = json_decode($json_string, , , 1);
I'm basing this only on the main documentation, so please test and let me know if it works.
Related videos on Youtube
Author by
tweety
Updated on November 29, 2020Comments
-
tweety over 3 years
Like:
float(1.2345678901235E+19) => string(20) "12345678901234567890"
Can it be done?
(it's for json_decode...)
-
Ashith almost 13 yearsThis is a good solution if you want to have a maximum number of decimal places. Based on the question, I'd change the above to
echo number_format($float,10,'.','');
giving it a max of 10 decimal places. (Arbitrary, but I'm pretty sure it should be higher than 0). -
tweety almost 13 yearsThe json value I get is not float, it's a really big integer, like 23453453245324532453253425. But it gets converted to float by json_decode. Will your solution always get me the original json value? :) (it seems to work though for the data I have now)
-
Karoly Horvath almost 13 yearsfloats have a limited precision, once your integers are large enough it won't work. should work for approx 14 digits. beyond that it might work, but could be sheer luck.
-
tweety almost 13 yearsThe value has 17 numbers right now. Do you know when it will stop to precisely convert the float?
-
Ashith almost 13 yearsYou can change the setting in the function call, see my answer.
-
tweety almost 13 yearsthat's the first thing I tried - JSON_BIGINT_AS_STRING, and I get: json_decode expects at most 3 parameters bla bla... and a undefined constant message
-
Karoly Horvath almost 13 yearsare these originally floats? because then they already lost precision. if they are ints try to send them as strings.
-
Ashith almost 13 yearsHa! I just tested and I got the same error, but with "expects at most 2 parameters". It looks like the 3rd parameter was added in 5.3 and the 4th in 5.4. So it would work if we upgraded our php.
-
netcoder almost 13 yearsAnyway, it's not even valid code, you can't omit arguments like that.
-
Ashith almost 13 yearscan't you? It says I passed in 4 parameters... Let me do a test.