|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2009-11-19 05:45 UTC] christian dot lawrence at calorieking dot com
Description:
------------
json_encode()-ing an integer when it is represented as floating point number results in a change of type when json_decode() decodes the output.
Examples of such floating point numbers are: -123.0, -1.0, 0.0, 1.0, 123.0
Reproduce code:
---------------
<?php
function jsonRoundTrip($f) {
$e = json_encode($f);
$d = json_decode($e);
var_dump($f, $e, $d);
echo "\n";
}
jsonRoundTrip(12.3); // This is a float
jsonRoundTrip(12); // This is an integer
jsonRoundTrip(12.0); // This is an integer represented as a float
jsonRoundTrip(0.0); // This is an integer represented as a float
?>
Expected result:
----------------
float(12.3)
string(4) "12.3"
float(12.3)
int(12)
string(2) "12"
int(12)
float(12)
string(4) "12.0"
float(12)
float(0)
string(3) "0.0"
float(0)
Actual result:
--------------
float(12.3)
string(4) "12.3"
float(12.3)
int(12)
string(2) "12"
int(12)
float(12)
string(2) "12"
int(12)
float(0)
string(1) "0"
int(0)
PatchesPull Requests
Pull requests:
HistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Oct 30 22:00:01 2025 UTC |
I tested the lib jansson (C) and it also keeps the fraction. json_t *array, *value; value = json_real(1.0); array = json_array(); json_array_insert(array, 0, value); printf("%s\n", json_dumps(array, 0)); Outputs: [1.0] I also tested go-lang and it gives integer value: import "encoding/json" fltB, _ := json.Marshal(1.0) fmt.Println(string(fltB)) Output: 1 Javascript returns integer as well: JSON.stringify(1.0) Output: 1 Kevin Israel suggested on my pull request to create another flag to json_encode (see https://github.com/php/php-src/pull/642#issuecomment-48993303). What do you guys think? I can add it to the PR.