huedaya.com/blog
just bunch of .md files
Laravel, Guzzle, and Decimal value in JSON

TIL, that its so difficult sending decimal number or float value with JSON in Laravel. The reason because Guzzle is ignoring any decimal number while sending the JSON payload.

php
$payload = [
    'decimal_value' => 1.5
];

$response = Http::withHeaders([
    'Content-Type' => 'application/json',
])->post(
    'https://webhook.site/0f34f6d8-be17-4bf8-9796-724c2b0c0c66',
    $payload,
);

The Http class (which extending Guzzle) will simply call json_encode() function to encode data causing float value stripped into integer.

json
{
    "decimal_value": 1
}

The solution actually pretty simple, you just need pass JSON_PRESERVE_ZERO_FRACTION as a second argument of json_encode(). However, for some reason the Guzzle's developer refuse to do this, the discussion is here. Since Laravel HTTP Client depend on Guzzle, it also giving similar behavior.

From the perspective of JSON it self, they want to be as simple as possible, so they treat integer or any decimal point as the same.

Solution: This might be not optimal, but personally I prefer to use string data type to send any decimal data rather using non-Guzzle approach. Then, the other end of the app parse the string back to float.

php
$payload = [
    'decimal_value' => "1.5"
];

Some pros/cons for this approach:

👍 Pros: Simpler code since we can keep using the Laravel's Http function
👎 Cons: Additional float parsing

So that's it!

Last update: 2024-03-11 09:00:12 UTC (4 months ago)