J
J
jeston2015-11-23 21:35:07
PHP
jeston, 2015-11-23 21:35:07

Does json_decode function reformat numbers?

I encountered strange behavior in my code:
1. a certain json arrives, from which I expect to get an array.

if ($data['prices']) {
        $prices = json_decode($data['prices'],true);

2. In the course of debugging, it turned out that $data['prices'] stores the value
string(28) "{"currency":"UAH","1":152.7}" string(28) "{"currency":"UAH","1":152.7}"

which is expected and suits me in principle.
3. But after json_decode, I find that the resulting array differs from the one I expect in the number format:
array(2) { ["currency"]=> string(3) "UAH" [1]=> float(152,7) } array(2) { ["currency"]=> string(3) "UAH" [1]=> float(152,7) }

Because of the comma in the number, the received value on the client throws the mathematical formula into Nan, which does not suit me. An additional difficulty is that it is impossible to edit the code in essence (well, except for var_dump and print_r).
Thank you in advance for your help.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Stalker_RED, 2015-11-23
@Stalker_RED

Probably the locale is taken into account.
You can use the JSON_BIGINT_AS_STRING flag and then floatval() if needed.

F
frees2, 2015-11-23
@frees2

setlocale(LC_ALL, 'ru_RU.utf8');
Header("Content-Type: text/html;charset=UTF-8");

G
Grigory Vasilkov, 2015-11-23
@gzhegow

first, convert the number to a string,
then replace the commas with dots
with a regular expression, and then the code to json
Do you like to do checks?
Check whether the original number through === is equal to what happened. If not, the commas are replaced. If yes, the comma either did not exist or was not replaced.

V
Vadim Kot, 2015-11-24
@vadimkot

You need to process the values ​​with number_format() something like this:

foreach ($prices as $key => $price) {
  $prices[$key]['UAH'] = number_format((float)$prices[$key]['UAH'], 2, '.', '');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question