开发者

PHP outputting numbers in exponential form

开发者 https://www.devze.com 2023-01-28 17:44 出处:网络
When i\'m outputting some of my double variables they\'re being written in exponenti开发者_如何学运维al form using fwrite. Can i set some defaults in PHP where whenever a variable is displayed (copied

When i'm outputting some of my double variables they're being written in exponenti开发者_如何学运维al 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.


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 to precision = 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)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消