Tomas Lucena
Tomas Lucena

Reputation: 1526

PHP - JSON_ENCODE Number converted to string. How to fix it?

I have the following variable with some coordinates from google maps:

$coordinates = '(22.2819939, 114.15444100000002)';

So to separate them I did the following:

$coor = explode(',',str_replace(array('(',')'),'',$coordinates));

Now I need to send this coordinates to an API in the following format:

$message = array("location"=>array($coor[1],$coor[0]));

I must send this in json so I encode the array but I am getting the coordinates as strings and not as number:

$toSend = json_encode($message);
result-> {"location":["114.15444100000002","22.2819939"]}

How can I avoid json to take the coordinates as string and take them as number instead?

I need this result:

{"location":[114.15444100000002,22.2819939]}

Upvotes: 2

Views: 5957

Answers (4)

Machavity
Machavity

Reputation: 31614

You'll need to convert them from string to float. So we simply map the array with a float conversion

$coor = array_map('floatval', $coor);

Upvotes: 3

Raptor
Raptor

Reputation: 54212

You can make use of number_format() to achieve your goal. See this example below:

$num_str = "114.15444100000002";
$str2float = (float)$num_str;
echo 'Cast to Float: ' . $str2float . PHP_EOL;

$num_format = number_format($num_str, 14);
echo 'With number_format(): ' . $num_format . PHP_EOL;

The result will be:

Cast to Float: 114.154441
With number_format(): 114.15444100000002

Proven number_format() works in your case.


p.s. you should make use of this function after you parsed the JSON. You should leave your values in string to prevent loss of precision during encoding and decoding.

p.s. As @jszobody mentioned, if the values are really coordinates, the precision should never require to go beyond 6 decimal places.

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

See JSON Predefined Constants and use the JSON_NUMERIC_CHECK option (but you will lose some precision):

$toSend = json_encode($message, JSON_NUMERIC_CHECK);

JSON_NUMERIC_CHECK (integer)

Encodes numeric strings as numbers. Available since PHP 5.3.3.

Upvotes: 3

wogsland
wogsland

Reputation: 9508

You can cast the strings into numbers

$number = (float) "114.15444100000002";

Upvotes: 1

Related Questions