josdejong / mathjs

An extensive math library for JavaScript and Node.js
https://mathjs.org
Apache License 2.0
14.44k stars 1.24k forks source link

BigNumber comparison wonky #2629

Closed f0o closed 2 years ago

f0o commented 2 years ago

Is there a way to compare two BigNumbers without casting them into Number which might screw them up?

const ONE = bignumber(1)
add(ONE,ONE) === add(ONE,ONE) # false
add(ONE,ONE) == add(ONE,ONE) # false

add(ONE,ONE) == add(ONE,ONE).toNumber() # true
add(ONE,ONE) === add(ONE,ONE).toNumber() # false

add(ONE,ONE).toNumber() == add(ONE,ONE) # true
add(ONE,ONE).toNumber() === add(ONE,ONE) # false

add(ONE,ONE).toNumber() == add(ONE,ONE).toNumber() # true
add(ONE,ONE).toNumber() === add(ONE,ONE).toNumber() # false
f0o commented 2 years ago

https://mathjs.org/docs/reference/functions/compare.html

josdejong commented 2 years ago

You are using the JavaScript equality operators == and === here. You should not rely on the JavaScript equality operators to do these comparisons, they do not know how to handle BigNumbers (or other non-primitive data types). The JavaScript operators for example compare the instance reference instead of the numeric value of the BigNumber.

To compare BigNumbers, you can for use: