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.

Share:
67,354

Related videos on Youtube

tweety
Author by

tweety

Updated on November 29, 2020

Comments

  • tweety
    tweety over 3 years

    Like:

    float(1.2345678901235E+19) => string(20) "12345678901234567890"

    Can it be done?

    (it's for json_decode...)

  • Ashith
    Ashith almost 13 years
    This 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
    tweety almost 13 years
    The 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
    Karoly Horvath almost 13 years
    floats 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
    tweety almost 13 years
    The value has 17 numbers right now. Do you know when it will stop to precisely convert the float?
  • Ashith
    Ashith almost 13 years
    You can change the setting in the function call, see my answer.
  • tweety
    tweety almost 13 years
    that'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
    Karoly Horvath almost 13 years
    are these originally floats? because then they already lost precision. if they are ints try to send them as strings.
  • Ashith
    Ashith almost 13 years
    Ha! 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
    netcoder almost 13 years
    Anyway, it's not even valid code, you can't omit arguments like that.
  • Ashith
    Ashith almost 13 years
    can't you? It says I passed in 4 parameters... Let me do a test.