MikeMcl / decimal.js

An arbitrary-precision Decimal type for JavaScript
http://mikemcl.github.io/decimal.js
MIT License
6.35k stars 480 forks source link

Precision is lost when working with cyclic division #221

Closed valerii15298 closed 1 year ago

valerii15298 commented 1 year ago

Seems there is a bug when preforming division with cyclic float numbers:

import {Decimal} from 'decimal.js';
const a1 = new Decimal("1");
const a2 = new Decimal("3");
console.log(a1.div(a2).toFraction()); // => [33333333333333333333, 100000000000000000000] but should get [1, 3]
console.log((a1.div(a2)).mul(3)); // => 0.99999999999999999999 but should get 1
MikeMcl commented 1 year ago

Did you not look at the result of a1.div(a2) before calling other methods on it?

console.log(a1.div(a2).toString())    // '0.33333333333333333333'

Look at the documentation for div and precision.

Also, notice that toFraction can take a maximum-denominator argument. For example:

console.log(a1.div(a2).toFraction(100).toString())    // '1, 3'