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

BigDecimal::of(0.00001)->getScale() is 6 #15

Closed
lx495707690 opened this issue Oct 10, 2018 · 2 comments
Closed

BigDecimal::of(0.00001)->getScale() is 6 #15

lx495707690 opened this issue Oct 10, 2018 · 2 comments

Comments

@lx495707690
Copy link

BigDecimal::of(0.0001)->getScale() is 4
BigDecimal::of(0.00001)->getScale() is 6
i find that "BigDecimal::of(0.00001)" the value is 10, and the scale is 6.
Can the value is 1, and the scale is 5 ?

@BenMorel
Copy link
Member

Hi, these discrepancies appear because you're using floating-point values:

echo $a = BigDecimal::of(0.00001); // 0.000010 (!)
echo $a->getUnscaledValue(); // 10
echo $a->getScale(); // 6

As advised in the README, you cannot trust a floating point value, and should always instantiate from an integer or string value:

echo $b = BigDecimal::of('0.00001'); // 0.00001
echo $b->getUnscaledValue(); // 1
echo $b->getScale(); // 5

Note that in this case, only the scale differs, the values are still equal:

var_export($a->isEqualTo($b)); // true

Where does the extra digit come from?

In this particular case, the reason is not a rounding error (a common issue with floating point numbers), but the fact that the value is converted to a string, then parsed:

echo (string) 0.00001; // 1.0E-5

The fact that it returns a number with value 10 and scale 6 is consistent with the fact that for the number 1.1E-5, one would expect value 11 and scale 6.

On the other hand, 1E-5 would return what you expect:

echo BigDecimal::of('1E-5')->getUnscaledValue(); // 1
echo BigDecimal::of('1E-5')->getScale(); // 5

In summary, no bug here, just use strings! 👍

@lx495707690
Copy link
Author

@BenMorel Thank you for your reply!

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

No branches or pull requests

2 participants