craftcms / element-api

Create a JSON API/Feed for your elements in Craft.
MIT License
498 stars 56 forks source link

Output of Float Numbers - Rounding Not Enforced #184

Open npruzaniec opened 9 months ago

npruzaniec commented 9 months ago

Description

I am using element-api to output JSON from Craft number fields (which are themselves limited to 1 or 2 decimal places) but for some reason, on output these are extended to 15 decimal places regardless of any PHP rounding rules I use in my controller classes.

Steps to reproduce

  1. Output number field in an API endpoint.
  2. View that output in the browser.

Additional info

Code:

return [
  'imperial' => [
    'value' => round($imperial, 2),
    'units' => $units->unit_label->imperial,
  ],
  'metric' => [
    'value' =>  round($metric, 2),
    'units' => $units->unit_label->metric,
  ]
];

Output:

"imperial": {
  "value": 10.800000000000001,
  "units": "in"
},
 "metric": {
  "value": 273,
  "units": "mm"
}
npruzaniec commented 9 months ago

I should add, the output is the same with or without the round() function.

npruzaniec commented 9 months ago

I found a server configuration that solved this for me after I discovered the issue did not exist when deployed to our staging server.

I am running this locally via DDEV. Adding a php.ini file to /craft/.ddev/php/php.ini with the following contents resolved the float precision issue for me:

[PHP]
serialize_precision = -1