Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Method to trim '0' digits after decimal point of a given number #52284

Merged
merged 3 commits into from
Jul 29, 2024

Conversation

gdebrauwer
Copy link
Contributor

What

A method on the Number class that trims zero digits after decimal point of a given number

Number::trim(12.0); // => 12

Use case

When a calculated number is returned in a JSON response and the number does not have any digits after the decimal point, then the JSON response will contain an integer instead of a decimal number.

response()->json(['average_rating' => (float) Review::query()->average('rating')]); // = 4.0

Results in

{"average_rating": 4}

When trying to assert that using assertJsonPath, this causes issues because the expected value is still a float while the JSON response contains an integer

// This fails because "4 !== 4.0"
$response->assertJsonPath('average_rating', $relevantReviews->average('rating'));

You can not just convert the expected number to an integer, because the expected number might have digits after the decimal points in other cases. The only way to fix this is JSON-encoding the expected number and then decoding it again.

// This does not fail anymore
$response->assertJsonPath('average_rating', json_decode(json_encode($relevantReviews->average('rating'))));

But this does not look very nice. That is where this new Number::trim($number) method comes into play:

// This does not fail
$response->assertJsonPath('average_rating', Number::trim($relevantReviews->average('rating')));

@gdebrauwer gdebrauwer changed the title [11.x] Method to trim zero digits after decimal point of a given number [11.x] Method to trim '0' digits after decimal point of a given number Jul 26, 2024
@taylorotwell taylorotwell merged commit 97fe718 into laravel:11.x Jul 29, 2024
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants