Encoding and decoding floats in json with PHP without losing precision -


i want decode json string php object , object again json string without losing precision floats numbers in json.

if run sample below output be:

json: string '{  "integer1": 10000,  "integer2": 100000999499498485845848584584584,  "float1": 1.121212,  "float2": 8.226347662837406e+09 }' (length=130) json without spaces [1]: string '{"integer1":10000,"integer2":100000999499498485845848584584584,"float1":1.121212,"float2":8.226347662837406e+09}' (length=112) object: object(myobject)[1]   public 'integer1' => int 10000   public 'integer2' => float 1.000009994995e+32   public 'float1' => float 1.121212   public 'float2' => float 8226347662.8374 json object [2]: string '{"integer1":10000,"integer2":1.000009994995e+32,"float1":1.121212,"float2":8226347662.8374}' (length=91) 

i want string [1] , [2] equal or @ least not loose precision. know decimal numbers can´t represented in php floats , know can use option json_decode($json, true, 512, json_bigint_as_string) represent number string in php. using option can re-generate original json object.

<?php  $json = <<<eot {  "integer1": 10000,  "integer2": 100000999499498485845848584584584,  "float1": 1.121212,  "float2": 8.226347662837406e+09 } eot;  // json_last_error_msg (php 5 >= 5.5.0) if (!function_exists('json_last_error_msg')) {     function json_last_error_msg() {         static $errors = array(             json_error_none             => null,             json_error_depth            => 'maximum stack depth exceeded',             json_error_state_mismatch   => 'underflow or modes mismatch',             json_error_ctrl_char        => 'unexpected control character found',             json_error_syntax           => 'syntax error, malformed json',             json_error_utf8             => 'malformed utf-8 characters, possibly incorrectly encoded'         );         $error = json_last_error();         return array_key_exists($error, $errors) ? $errors[$error] : "unknown error ({$error})";     } }  class myobject {     /** @var  int|float */     public $integer1;     /** @var  int|float */     public $integer2;     /** @var  int|float */     public $float1;     /** @var  int|float */     public $float2;      public function __construct($json)     {         $this->fromjson($json);     }      public function fromjson($json)     {         $result = json_decode($json);          if (json_last_error() != json_error_none) {             die('json_decode error: '.json_last_error_msg());         };          $this->integer1 = $result->integer1;         $this->integer2 = $result->integer2;         $this->float1 = $result->float1;         $this->float2 = $result->float2;     }      public function tojson()     {         $json =  json_encode($this);          if (json_last_error() != json_error_none) {             die('json_decode error: '.json_last_error_msg());         };          return $json;     } }  echo 'json: '; var_dump($json);  echo 'json without spaces [1]: '; var_dump(preg_replace('/\s+/', '', $json));  $object = new myobject($json);  echo 'object: '; var_dump($object);  echo 'json object [2]: '; var_dump($object->tojson()); 

i suppose add metadata object , indicate if string property number in original json string have parse json self , not using json_decode function.

i have read lot of posts on matter of them said how convert json object (using string) not how convert again object original json number in json.

if want play sample: http://sandbox.onlinephpfunctions.com/code/8d934874c93c4574d886dbbf645a6763ba1ba131

what created json string?

while theoretically correct accurate degree of craziness normal php programmer doesn't need. values not representable in 32 bit (or in 64 bit) php memory floats or integers. way, online link posted uses 32 bit php. when php decodes json, tries accurate possible when representing values in memory. did notice integer2 overflowed decoded float there loss of precision, no overflow? since never able represent these insanely accurate values in memory, when encode object again, logically similar different json string.

you should ask yourself, why need json string identical original representation? if need degree of accuracy, consider using java can use higher precision data types (such biginteger). php not best tool high accuracy stuff this. (php 5 anyway).

suggested reading:


Comments