user1616685
user1616685

Reputation: 1340

php JSON encode float number

it seems a simple thing: I would like to encode:

echo json_encode(array('lol' => 104564563225.1));

gives:

{"lol":1.0e+11}

I would like to be the output:

{"lol":104564563225.1} 

How can this be achieved? some more server data just in case:

PHP Version 5.6.0
System  Windows NT XXXXXXXXXXXXXX 6.3 build 9200 (Windows Server 2012 R2
Standard Edition) i586
Build Date  Aug 27 2014 11:49:46
Compiler    MSVC11 (Visual C++ 2012)
Architecture    x86
Configure Command   cscript /nologo configure.js "--enable-snapshot-   build" "--enable-debug-pack" "--disable-zts" "--disable-isapi" "--disable-nsapi" "--without-mssql" "--without-pdo-mssql" "--without-pi3web" 
"--with-pdo-oci=c:\php-sdk\oracle\x86\instantclient_12_1\sdk,shared" "--with-oci8-12c=c:\php-sdk\oracle\x86\instantclient_12_1\sdk,shared" "--with-enchant=shared" "--enable-object-out-dir=../obj/" "--enable-com-dotnet=shared" "--with-mcrypt=static" "--without-analyzer" "--with-pgo"
Server API  CGI/FastCGI
Virtual Directory Support   disabled
Configuration File (php.ini) Path   C:\Windows
Loaded Configuration File   C:\Program Files (x86)\PHP\v5.6\php.ini 

Upvotes: 0

Views: 2018

Answers (1)

axiac
axiac

Reputation: 72177

The string representation of floating point numbers depends on the precision configuration (see its documentation on php.ini directives).

Also, echo(104564563225.1); should display the same value as json_encode() produces.

By default the precision is 14 and with this value your code displays:

{"lol":104564563225.1}

Maybe it has a lower value on your system.

You can get its current value from your script using ini_get():

echo(ini_get('precision'));

and you can change it using ini_set():

ini_set('precision', '14');

Of course, searching and changing it in your php.ini is another option, if it's available to you.

Upvotes: 1

Related Questions