Reason#
Why does JavaScript have precision issues?
Solution#
It is recommended to use third-party libraries such as bignumber.js, decimal.js, or math.js to solve the precision issues in JavaScript. These libraries avoid floating-point precision loss by re-implementing the calculation logic.
- bignumber.js and decimal.js are popular choices that provide arbitrary-precision decimal arithmetic.
- math.js is a more comprehensive math library that not only solves precision issues but also supports symbolic computation, matrix operations, and more.
The code examples in this article use bignumber.js to implement basic arithmetic:
// Addition
const accAdd = (arg1, arg2) => {
return new BigNumber(arg1 ?? 0)
.plus(new BigNumber(arg2 ?? 0)).toNumber();
}
// Subtraction
const accSub = (arg1, arg2) => {
return new BigNumber(arg1 ?? 0)
.minus(new BigNumber(arg2 ?? 0)).toNumber();
}
// Multiplication
const accMul = (arg1, arg2) => {
return new BigNumber(arg1 ?? 0)
.times(new BigNumber(arg2 ?? 0)).toNumber();
}
// Division
// arg1 is the dividend; arg2 is the divisor.
// Formula: dividend / divisor = quotient
const accDiv = (arg1, arg2) => {
if(args2 === 0) {
throw new Error('Divisor cannot be 0');
}
return new BigNumber(arg1 ?? 0)
.div(new BigNumber(arg2)).toNumber();
}