1

I have a string:

{"lat":28.67167520663993,"lng":77.23913223769534}

When I use:

$json = json_decode($json['latlng'] , true); 
echo "<pre>";print_r($json );

then output value is:

Array:

(
    [lat] => 28.67167520664
    [lng] => 77.239132237695
)

but result is different and truncated

I need original value how can i do it?

Sunil
  • 3,404
  • 10
  • 23
  • 31

3 Answers3

2

As much i understand below is my input:

1) The value you providing is float value. It's float problem not json problem.

2) The workaround is you can wrap your value in double quotes "28.67167520663993". It will give you proper output. Code shown below

$a = '{"lat":"28.67167520663993","lng":"77.23913223769534"}';
print_r(json_decode($a,true));

3) Float is going to round till 3 digit precision by default in my system.
4) Another method to prevent set ini_set('precesion',15). It will not round up till 15 digits.

<?php
ini_set('precision', 15);
$a = '{"lat":28.67167520663993,"lng":77.23913223769534}';
print_r(json_decode($a,true));

5) Bugs already reported here. Above is different way of prevention till php introduce some solution for it.

Ashish Tiwari
  • 1,919
  • 1
  • 14
  • 26
1

Try this :

$json = '{"lat":28.67167520663993,"lng":77.23913223769534}';
$json = preg_replace('/:\s*(\-?\d+(\.\d+)?([e|E][\-|\+]\d+)?)/', ': "$1"', $json);

$jsond = json_decode($json , true); 
echo "<pre>";print_r($jsond );
vikalp
  • 330
  • 2
  • 9
0

It's matter of numeric precision. You can't do much about that using json_decode() unless you want to parse JSON file yourself and use GMP to handle your values.

See notes in docs: https://secure.php.net/manual/en/language.types.float.php

Warning

Floating point precision Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

Community
  • 1
  • 1
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141