MikeMcl / bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic
http://mikemcl.github.io/bignumber.js
MIT License
6.65k stars 742 forks source link

Handling Repeating decimal #225

Closed upupming closed 5 years ago

upupming commented 5 years ago

Hi, this is a noob question, you can see the result:

let a = new BigNumber(1).dividedBy(3);
let b = a.multipliedBy(3);
console.log(b);
console.log(b.isEqualTo(new BigNumber(1)));
// 0.99999999999999999999
// false

Is it possible to make the value of b be 1 instead of 0.99999999999999999999.

I just want to compare two big numbers, but I always got false when there is repeating decimal during the calculation.

MikeMcl commented 5 years ago

You just need to round the result before you make the comparison. For example, here are three different ways of rounding a BigNumber:

x = b.decimalPlaces(10);
y = b.precision(10);
z = b.integerValue();
x.isEqualTo(1) && y.isEqualTo(1) && z.isEqualTo(1);    // true
upupming commented 5 years ago

thanks for your explanation.