BigNumber.js and Rounding Error

I’m at my wits’ end trying to make a calculator app return the expected values. I added BigNumber.js to mitigate the problems with rounding error. It works for the common cases like 0.1 + 0.2, but it’s actually worse for 1 / (1 / 9). This is the result: How can I make this work for all inputs?

The short answer is that you can’t without infinite precision

There’s more than one issue with finite precision, and there’s a few strategies for mitigation of the problems

Division is quite a bit trickier than the other operations, bignumber can automatically figure out how many points of precision it should use for the other operations, but for division it’s not possible in general (consider 1/3)

Instead you should consider setting the precision you care about for the division operations yourself (see the readme)

Edit: I should note that it’s hypothetically possible with arbitrary length integers in a fraction, but the numerator and denominator tend to quickly blow up to infinity with repeated operations, which for arbitrary length integers becomes very slow

1 Like

Thank you for the straight answer. I was about to start actually tearing my hair out.

I noticed that rounding to the greater of the two precisions worked for addition and subtraction, and rounding to the sum of the two worked for multiplication, but division was a nightmare no matter what I did. I’ll take another look at the docs.