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

Specify decimal amount when converting to float #40

Closed
wants to merge 7 commits into from

Conversation

rogervila
Copy link

@rogervila rogervila commented Apr 12, 2020

I had to compare 2 float values using BigDecimal class, but I was getting an unexpected result because those floats had no decimals:

BigDecimal::of($result1)->toFloat(); // 123.0
BigDecimal::of($result2)->toFloat(); // 123

return $result1 === $result2; // returns false

With this solution, specifying the amount of decimals will get expected results

BigDecimal::of($result1)->toFloat(1); // 123.0
BigDecimal::of($result2)->toFloat(1); // 123.0

return $result1 === $result2; // returns true

@BenMorel
Copy link
Member

Hi, you're misusing floats. You should never compare them for equality, they're imprecise by design.

Your PR doesn't make much sense: if I call BigDecimal::of(123)->toFloat(2), I get the exact same value as if I call BigDecimal::of(123)->toFloat(0)!

Bottom line: use BigDecimal to compare your decimal values, only convert to float if you have a compelling reason to do so!

@rogervila
Copy link
Author

Ok, I will change the strategy. Thank you for your advice :)

@rogervila rogervila closed this Apr 12, 2020
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