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

mathjs and decimal.js output different results #215

Closed alexandrzavalii closed 1 year ago

alexandrzavalii commented 1 year ago

Can anyone please explain why I see this inconsistency in results between mathjs in decimal.js?

const num1 = 38970.850000000006;
const num2 = 0.03175532;

const results = [
  ["raw JS", num1 * num2],
  [
    "decimal.js",
    Decimal(num1).mul(num2).toNumber()
  ],
  ["mathjs", mathjs.multiply(num1, num2)]
];
console.log("38970.850000000006 * 0.03175532 =");
console.table(results);

Screenshot 2023-02-04 at 15 48 19

josdejong commented 1 year ago

I think reading up on floating point numbers, precision, and round-off errors will give you all the answers. And secondly, in your example, you feed mathjs numbers. In that case, mathjs will multiply numbers and is not using higher precision Decimal.js.