Search code examples
javascriptbignum

When should I use the bignumber library?


I am trying to understand when to use the bignumber library.

Question 1). As we know, JavaScript has an upper limitation on the Number type which is 2^53, but it also has another type, BigInt, which doesn't have a limit. Why would we use the bignumber library? Is it because it also works with decimals? Are there any other reasons?

Question 2) Let's say I have a x = new BigNumber(10000000000000000000); and now I want to multiply this by 30. Should I also transform 30 to BigNumber first and then multiply or would this be okay: 30 * x? It seems like that I didn't transform 30 to BigNumber and it still works correctly. When should I use mul from the bignumber library?


Solution

  • Why would we use bignumber library? is it because it also works with decimals?

    Yes. A bignumber library typically works with arbitrary-precision floating-point numbers, while a bigint library (or also the builtin data type) can only handle integers.
    In addition, there are quite a few libraries that implement big integer math which came into existence before the native support of BigInt in JavaScript, a rather recent addition to the language. This also means a library is necessary in older browsers.

    Now I want to multiply this by 30. Should I also transform 30 to bigNumber first?

    No, this is usually not necessary (but of course depends on the library).

    would this would be okay: 30 * x?

    No, that would not be ok. If you're working with a bignumer library, you will need to use its methods (like x.multiply(30)), not the * operator which only works with JavaScript's builtin data types.