-1

I am having a very different question. For some reason, when the json_encode function receives a variable that has the value assigned by a multiplication, the echo result will be a different value than expected. Example:

<?php
  $test = 1.1 * 122;
  echo json_encode(array("test" => $test)); // prints {"test":134.20000000000002}
  echo $test; // prints 134.2
?>

For some reason, it doesn't work on every version of PHP, so I created a snippet on a tester that works: Online Tester

Why does this happen?

Lucius
  • 1,246
  • 1
  • 8
  • 21
  • 4
    This is a [side effect of floating point math](https://floating-point-gui.de/basic/). Use `round()` if you need a specific precision. – Alex Howansky Sep 18 '19 at 14:57
  • Yes, but my question would be why this happens, since "122 * 1.1" doesn't give this value, would you know? – Lucius Sep 18 '19 at 15:03

1 Answers1

-1

Just use round function

  $test = round(1.1 * 122, 2);
  echo json_encode(array("test" => $test));
Omer Farooq
  • 3,754
  • 6
  • 31
  • 60
  • Yes, but my question would be why this happens, since 122 * 1.1 doesn't give this value, would you know? – Lucius Sep 18 '19 at 15:03