|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2014-10-09 14:00 UTC] vwirus at o2 dot pl
Description:
------------
json_decode rounding floats to 3 digits precision. My precision setting in php.ini shows 14.
Test script:
---------------
$tmp = json_decode('{"number":1000000.66599998}', true);
if (false !== strpos((string) $tmp['number'], '1000000.666')) {
echo PHP_EOL, 'WRONG', PHP_EOL;
}
else {
echo PHP_EOL, 'OK', PHP_EOL;
}
var_dump($tmp, $tmp['number']);
Expected result:
----------------
After decode the value of $tmp['number'] should be 1000000.66599998.
Actual result:
--------------
After decode the value of $tmp['number'] shows be 1000000.666 (it rounds real value with 3 digits precision)
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 22 21:00:01 2025 UTC |
14 digits of precision goes all the way to 1000000.66599998 ^ so yes, it will round to .666. By the way, "significant digits" are not just the decimal places so it rounded to 10 digits, not 3. Push your precision up to 15 or more and it will save as you want.> But it's not very stright forward and not possible in shared hosting. All you need to add is ini_set("precision", 15);You not always able to call ini_set, and i high load apps you shouldn't. Also let's say you dealing with numbers up to 18 significant digits. So you're setting: ini_set('precision', 18); but: $tmp = json_decode('{"number": 1000000.66599998}', true); var_dump($tmp); displays: array(1) { ["number"]=> float(1000000.66599997994) } So important information is lost!