I am retrieving some values stored as string which have up to 15 decimal places. I need to json_encodeit and pass it on to javascript as numeric value. So I tried (float)$number, but the number gets rounded-off in this approach. How else can I convert it to number without any rounding?
2 Answers
You should use the GMP library in PHP whenever number precision is important. You may have to enable it inside of your php.ini settings. Search for...
;extension=php_gmp.dll
and change it to
extension=php_gmp.dll
and then you'll be able to use the GMP objects.
Comments
If you want to preserve those decimals: don't parse it. Any number converted to float is subject to precision loss. Can't you just print the variable as received in JS?
5 Comments
Bluemagica
My problem is, the other coder doing the js, asked me to provide the output as numeric not a string, which it is by default. I also tried double, but....
h2ooooooo
@Bluemagica That's because it's the same in PHP
Bluemagica
True, but then again that means there is no native way of doing this! sigh!
h2ooooooo
@Bluemagica Not natively. Do you need to do calculations with it?
Izkata
@Bluemagica Output it as a string. The javascript doesn't need to know:
echo "var foo = " . $num_as_string . ";"; - the only time you need to actually do the conversion is if you manipulate the number inside the PHP.
print_r(json_decode('{ "test": 3.1234567890123456789 }'));orecho json_encode([ 'test' => 3.1234567890123456789 ]);