Json Floating Point


#1

I am as problem to returns in slim a float number with only 2 decimal places

  "shippingQuotes": [
    {
      "shippingCost": 24.57000000000000028421709430404007434844970703125,
      "deliveryTime": {
        "expedition": 0,
        "transit": 14,
        "total": 14
      },
      "shippingEstimatedId": 4286128282,
      "shippingMethodId": 1,
      "shippingMethodName": "Standard",
      "shippingMethodDisplayName": "Correios"
    },
    {
      "shippingCost": 42.159999999999996589394868351519107818603515625,
      "deliveryTime": {
        "expedition": 0,
        "transit": 13,
        "total": 13
      },
      "shippingEstimatedId": 4286128282,
      "shippingMethodId": 41,
      "shippingMethodName": "Standard",
      "shippingMethodDisplayName": "Rodonaves"
    }
  ]
}

#2

This has nothing to do with Slim itself, this is a result of how floating point numbers are represented internally which means that certain values can not be represented accurately.

One way to deal with this is to round to the number of decimal places you require. Another way is to use strings instead of floats. I prefer the rounding approach since it preserves the type (number).

Also, if these values are coming from a database (lets assume Mysql/MariaDB) you may want to switch your datatype from float/double to “decimal” which allows for a non-lossy representation while still interpreting the values as a number.


#3

I already tried to lease but the number continues as several decimal places, php number_format and rand, but without success


#4

You could try to round the numbers:
Edit:

$price = 24.57;

echo json_encode(round($price, 2));
echo "\n";
echo json_encode(number_format($price, 2));

Result

24.57
"24.57"

#5

Some numbers just can’t be represented in binary. It’s quite a common problem. You usually need to use something like BCD, or I would recommend using Money: http://moneyphp.org/en/latest/

When you’re encoding currency, do it as a string. It’s not a float. Never store or manage it as a float.

Please read the linked articles on moneyphp.org for more details


#6

Interestingly, this video has just been suggested to me on YouTube :grin: