tweety
tweety

Reputation: 313

Convert float to string in php?

Like:

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

Can it be done?

(it's for json_decode...)

Upvotes: 31

Views: 94118

Answers (8)

Mychi Darko
Mychi Darko

Reputation: 31

One funny way is to use json_encode()

json_encode($float, JSON_PRESERVE_ZERO_FRACTION)

Upvotes: 0

Sam Azer
Sam Azer

Reputation: 186

I often use:

$v = float(1.2345678901235E+19);
$s = "{$v}";

Not sure if there may be any "gotcha's" associated but it generally works for me.

Upvotes: 0

The only way to decode a float without losing precision is to go through the json and frame all the floats in quotation marks. By making strings of numbers.

PHP json_decode integers and floats to string

Upvotes: 0

Astrotim
Astrotim

Reputation: 2172

I solved this issue by passing the argument JSON_BIGINT_AS_STRING for the options parameter.

json_decode($json, false, 512, JSON_BIGINT_AS_STRING)

See example #5 in the json_decode documentation

Upvotes: 0

lubart
lubart

Reputation: 1838

$float = 0.123;
$string = sprintf("%.3f", $float); // $string = "0.123";

Upvotes: 21

Anthony
Anthony

Reputation: 37085

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.

Upvotes: 2

Karoly Horvath
Karoly Horvath

Reputation: 96366

echo number_format($float,0,'.','');

note: this is for integers, increase 0 for extra fractional digits

Upvotes: 57

Alnitak
Alnitak

Reputation: 340055

A double precision floating point number can only contain around 15 significant digits. The best you could do is pad the extra digits out with zeroes.

Upvotes: 0

Related Questions