PHP outputting numbers in exponential form
-
08-10-2019 - |
문제
When i'm outputting some of my double variables they're being written in exponential form using fwrite. Can i set some defaults in PHP where whenever a variable is displayed (copied or stored) it always happens in decimal format?
To be precise the problem occurs when i use the json_decode method on a json string which contains a double value (which is not in exponential form). That double value after converting an an object becomes exponential.
해결책
Assuming the numbers are still floats when being written (as opposed to strings), this is one way of doing it:
echo rtrim(sprintf("%0.15f", $x), "0.");
I'm not sure if there's a cleaner way or not. But basically this uses sprintf
to print a maximum of 15 decimal places, and then trims off any trailing 0
or .
chars. (Of course, there's no guarantee that everything will be rounded nicely with trailing zeros as you might expect.)
If you just want a fixed size, then you can adjust the 15
and remove the rtrim
.
다른 팁
I had a similar problem where json_decode
was converting recent twitter/tweet IDs into exponential numbers.
I solved it by upping PHP's float precision, which can be done a different few ways...
- find the
precision
value in your php.ini and change it toprecision = 20
- add
ini_set('precision', 20);
to your PHP app - add
php_value precision 20
to your app's .htaccess or virtual host file
Otherwise, if you're fine with having your BIGINT
converted to a string and you have PHP 5.3+ you can also pass a flag to json_decode
like so: json_decode($json, true, 512, JSON_BIGINT_AS_STRING)