MikeMcl / bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic
http://mikemcl.github.io/bignumber.js
MIT License
6.63k stars 743 forks source link

Substraction of small values yields incorrect results #326

Closed hafidk closed 2 years ago

hafidk commented 2 years ago

Hi, been encountering the following issue when substracting a small decimal from an extremely big number:

new BigNumber("999999999999998.8").minus("0.1").toNumber() Yields 999999999999998.8 again,

same goes for:

new BigNumber("999999999999998.8").minus("0.00001").toNumber()

shuckster commented 2 years ago
const result1 = new BigNumber("999999999999998.8").minus("0.1")
const result2 = new BigNumber("999999999999998.8").minus("0.00001")

console.log('result1', result1.toString())
// 999999999999998.7

console.log('result1', result1.toNumber())
// 999999999999998.8

console.log('result2', result2.toString())
// 999999999999998.79999

console.log('result2', result2.toNumber())
// 999999999999998.8

BigNumber exists to get around issues with the native number type.

You have to work with strings. Well, unless you can guarantee that your arithmetic will never result in a number that cannot be accurately represented by JavaScript's IEEE-754 BFP implementation, in which case you don't really need to use BigNumber at all.

windkind88 commented 2 years ago

How do you display higher accuracy? example

const result1 = new BigNumber("\
99999999999999999999999.8\
").minus("0.1")
console.log('result1', result1.toString())

now: result1 9.99999999999999999999997e+22 i hope: 99999999999999999999999.7

shuckster commented 2 years ago
result1.toFixed()