MikeMcl / decimal.js

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

very bad issue: 1 / 9 * 9 != 1 #152

Closed vital0872 closed 4 years ago

vital0872 commented 4 years ago

I have identified, in my opinion, an unpleasant case. A very simple expression is miscalced.

let x = new Decimal ("1")
let y = x.div ("9").mul ("9")
y.toString () //  => 0.99999999999999999999

The expression "1 / 3 * 3" is also miscalced.

Config: defaults Environment: Google Chrome

Even the native type "Number" doesn’t allow this.

vmukhachev commented 4 years ago

this is, probably, by design, decimal representation cannot store 1/9 exactly, use rounding or use rational type like provided by big-rational on npm

MikeMcl commented 4 years ago

I agree that it is an unpleasant case, but 0.99999999999999999999 is very close to one, and can easily become one with a little rounding as suggested above. See toSignificantDigits or toDecimalPlaces.