JS fractions for big numbers with no precision lose #2957
-
Big numbers with fraction support: I want to perform math operation with no precision loss. import {Decimal} from 'decimal.js';
const a1 = new Decimal(1);
const a2 = new Decimal(3);
console.log(a1.div(a2).toFraction()); // should be `1/3` but I get `33333333333333333333/100000000000000000000` Next I tried fraction.js but it does not work with large numbers, for example: import Fraction from 'fraction.js';
const n1 = new Fraction("99999999999999999999999999999999999999999999999");
const n2 = new Fraction("99999999999999999999999999999999999999999999990");
console.log(+(n1.sub(n2))) // should be 9, but I get 0 Are there any solutions to work with relative large numbers(lets say same as I checked out that import * as math from "mathjs";
const a1 = math.fraction(math.number("99999999999999999999999999999999999999999999999"))
const a2 = math.fraction(math.number("99999999999999999999999999999999999999999999990"))
console.log(+(math.subtract(a1, a2))) // should be 9 but I get 0 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Please ask yourself why you think you need that. There is no silver bullet. There are roughly the following options:
Docs: https://mathjs.org/docs/datatypes/numbers.html#roundoff-errors On a side note: your last example creates a regular |
Beta Was this translation helpful? Give feedback.
A
BigFraction
library would be very nice too, given that all operations that you need are supported by the library. (Isn't the regular fraction.js library good enough though?... test it against your realistic calculations ;) )