Framework: JSON Response with float values gives wrong decimals

Created on 8 Mar 2018  路  3Comments  路  Source: laravel/framework

  • Laravel Version: 5.6.9
  • PHP Version: 7.1.8
  • Os: OSX using MAMP v4.2.1

Description + Steps To Reproduce::

Hello guys,

I'm trying to do a simple JSON response as follows:

namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;

class TestController extends Controller {

public function getData() 
{
       return response()->json(["data" => 20.51]);
}

}

The output is:

{
    "data": 20.510000000000001563194018672220408916473388671875
}

Which is wrong and I have to truncate all my float values from the frontend.

Any ideas?

Thank you!

Most helpful comment

You're probably running with default php configuration that is hiding data from you. Use ini_set('precision', 17') to see how your floating point number actually look. Source: https://www.leaseweb.com/labs/2013/06/the-php-floating-point-precision-is-wrong-by-default/

The number of decimals in floating point numbers in json is controlled via another setting, serialize_precision since PHP 7.1 and this RFC. The goal is to send as much data as possible to the client to avoid rounding errors.

There's nothing in this issue that relates to Laravel.

All 3 comments

I am having the same issue.

You're probably running with default php configuration that is hiding data from you. Use ini_set('precision', 17') to see how your floating point number actually look. Source: https://www.leaseweb.com/labs/2013/06/the-php-floating-point-precision-is-wrong-by-default/

The number of decimals in floating point numbers in json is controlled via another setting, serialize_precision since PHP 7.1 and this RFC. The goal is to send as much data as possible to the client to avoid rounding errors.

There's nothing in this issue that relates to Laravel.

Maybe a little late but I also had the same problem, found the solution here.

https://stackoverflow.com/a/64413695/11567022

Was this page helpful?
0 / 5 - 0 ratings