Coder-Spirit / php-bignumbers

A robust library to handle immutable big numbers inside PHP applications
MIT License
131 stars 29 forks source link

Critical: huge calculation error on integer numbers with the type "float" #55

Closed uvarovserge closed 7 years ago

uvarovserge commented 7 years ago

What is going on here? I couldn't understand what this line (and the concept of "natural scale") is for:

https://github.com/Litipk/php-bignumbers/blob/master/src/Decimal.php#L102

When you have a scale set, it wrongly adds zeroes for some reason:

define('PRECISION', 8); print Decimal::create(4, PRECISION)->asFloat(); // prints "4"; print Decimal::create(4.0, PRECISION)->asFloat(); // prints "400000000"; print Decimal::create((float)4, PRECISION)->asFloat(); // prints "400000000";

Was your goal to arrive at "4.00000000" instead?

uvarovserge commented 7 years ago

By the way, I'm using 0.8.3 version

uvarovserge commented 7 years ago

I'm currently using this as a hackish workaround

            // ...right after $naturalScale is calculated
            if (fmod($fltValue, 1.0) === (float)0) {
                $strValue .= '.';
                $naturalScale += 1;
            }
castarco commented 7 years ago

Hi @uvarovserge , I'm sorry for being so slow responding to the bug report. I'm doing the regression tests and preparing the fix.

uvarovserge commented 7 years ago

Updated the library now, can confirm, https://github.com/Litipk/php-bignumbers/pull/56 didn't do the trick in some cases, and your latest commits have solved all the issues. Thanks!