My application receives a JSON request from a different application with maximum 18 digit floating point value. Now when i try to decode the JSON request data the floating point value with digit greater than 12 gets round off to maximum 12 digits but my application should need to handle the request and treat the floating point number with same precision as this value is used to verify the authenticity of the request.
{
"value2": 12.2256,
"value": 18.4446359017678
}
after JSON_DECODE gets converted to
array("value" => 18.444635901768, "value2" => 12.2256)
. Please advise as i have already used the ini_set('precision' 18) but it converts all the floating point number to 18 digits. Thank you
welcome to StackOverFlow
if you wanna only set precision to 16 or more, you should set 16 for precision ini. but pay attention if you set specif precision more than 16 and your floating numbers be lower than 17, php make sured to your float numbers convert to 17 digit numbers. such as:
ini_set('precision', 17);
$json = '{"value":16.1}';
$json = json_decode($json, true);
var_dump($json['value']); // value convert from float(16.1) to float(16.100000000000001)
the best solution for this problem is disable precision with putting -1 to precision ini:
ini_set('precision', -1);
$json = '{"value":18.4446359017678}';
$json = json_decode($json, true);
var_dump($json['value']); // float(18.4446359017678)
but there is an another simple solution and it is convert your float number type to string. when your number types be string, php processes for float numbers will be disable:
$json = '{"value":"18.4446359017678"}';
$json = json_decode($json, true);
var_dump($json['value']); // string(16) "18.4446359017678"