MikeMcl / bignumber.js

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

Small number #298

Closed fireridlle closed 2 years ago

fireridlle commented 3 years ago

I'm working with cryptocurrency. And for some assets, my available balance is pretty small. When passing it to BigNumber, it behaves strangely and then breaks all calculations that I do. Any suggestion on how to handle this?

new BigNumber('0.0000004').toNumber() // "4e-7"
MikeMcl commented 3 years ago

Your example doesn't show any broken calculations, and there shouldn't be any.

JavaScript stringifies numbers with an exponent at or lower than -7 to exponential notation, so if, for example, you type 0.0000004 in a browser console and press return it will display 4e-7.

If you don't want exponential notation, you can use, for example,

new BigNumber('0.0000004').toFixed()    // '0.0000004'
dangnguyen1004 commented 1 year ago

But I don't want to set it fixed to 7. For example, if I have 0.000002, then it displays 0.0000020 when I use toFixed(7). I want it to not display the last zero but still display the maximum 7 number of decimals.

shuckster commented 1 year ago
function trunc(numStr) {
  return numStr.at(-1) === "0"
    ? numStr.slice(0, numStr.lastIndexOf("0"))
    : numStr;
}

trunc(new BigNumber("0.000002").toFixed(7));
// 0.000002

trunc(new BigNumber("0.00000225").toFixed(7));
// 0.0000023
dangnguyen1004 commented 1 year ago

I discovered the solution by not passing any parameters to the toFixed() method. Sorry for my silly