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!
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.
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_precisionsince 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.