Req #68456 [Asn->Wfx]: json_decode should be able to treat all numbers as strings
| From: | bukka@php.net | Date: | Sun, 15 Mar 2015 16:53:05 +0000 |
| Subject: | Req #68456 [Asn->Wfx]: json_decode should be able to treat all numbers as strings | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-191403@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=68456&edit=1
ID: 68456
Updated by: bukka@php.net
Reported by: admin at bittylicious dot com
Summary: json_decode should be able to treat all numbers as
strings
-Status: Assigned
+Status: Wont fix
Type: Feature/Change Request
Package: JSON related
Operating System: Linux Wheezy
PHP Version: 5.4.35
Assigned To: bukka
Block user comment: N
Private report: N
New Comment:
The problem is that this number will never get saved with the full precision. You can influence the
number of visible decimal places with setting ini precision as it is in
http://3v4l.org/80iCh
However as you can see the number is rounded because the internal float representation (C double
type) cannot contain the whole number. So this is not JSON related. and any conversion to string
can't fixed. The thing is that json_decode is using normal string conversion.
So this can't be fixed in the JSON. I'd recommend you not to save the number to the the
float at all but represent it as a string.
Previous Comments:
------------------------------------------------------------------------
[2014-11-19 22:18:56] admin at bittylicious dot com
Description:
------------
There should be an option that can be passed to json_decode that will allow numbers to be handled as
strings. This is because some numbers can not be represented in a float properly. In reality, JSON
is often used as a transport layer, and it's very useful to keep this accuracy.
One example in practice where this has caused issues is when dealing with Dogecoin (a Bitcoin
derivative). Dogecoin has eight decimal places, and because each Dogecoin is worth only a tiny
fraction of a cent, they can often be represented as tens or hundreds of millions of Dogecoins. When
you're dealing with finance, it's essential not to lose precision. The only workaround I
have is to use a complicated preg_replace to add quotes to the original JSON string, which is nasty.
Test script:
---------------
<?php
print_r(json_decode('{"test":1234567890.12345678}'));
?>
Output:
stdClass Object
(
[test] => 1234567890.1235
)
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=68456&edit=1