Coder Social home page Coder Social logo

Comments (2)

BenMorel avatar BenMorel commented on August 22, 2024

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! πŸ‘

from math.

lx495707690 avatar lx495707690 commented on August 22, 2024

@BenMorel Thank you for your reply!

from math.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.