brick / math

Arbitrary-precision arithmetic library for PHP
MIT License
1.78k stars 75 forks source link

Specify decimal amount when converting to float #40

Closed rogervila closed 4 years ago

rogervila commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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