0

Using PHP I am trying to add a float number 0.3 to a object then encode it but when I encode the object the float gets changed to a long decimal number.

<?php
   $test = 0.3;
   $data = new stdClass();
   $data->test = $test;
   echo json_encode ($data);
?>
Motorhomer
  • 15
  • 5
  • 1
    Works as expected (with a minor fix): https://3v4l.org/ZQmih (output is `{"test":0.3}`). But this might be an interesting read: [Is floating point math broken?](https://stackoverflow.com/q/588004/1941241) – rickdenhaan Oct 02 '21 at 12:46
  • Sorry made type error on line three of code. Just edited. I get {"test":0.29999999999999999} in result were I was expecting {"test":0.3}. I will have a read of the link you posted – Motorhomer Oct 02 '21 at 12:55

1 Answers1

0

Save your number as a string :

   $test = "0.3";
Camille
  • 847
  • 1
  • 7
  • 19