Three non-standard types of numbers in JavaScript and two libraries

    JavaScript has one type of number by default - Number. Although it is of course divided into Int and Float, although it is expressed in a little (for example, in the parseInt functions - parseFloat).
    In this case, large numbers (both Int and Float) are shortened, and fractions are reduced to decimal and rounded. Both are not always good, so libraries have appeared that offer new classes for unusual numbers.

    BigInt

    Numbers (both Int and Float) are shortened to 15 characters. In Int, the remaining digits are stored as zeros. Example:
    >> 100000000000000000111
      100000000000000000000
    

    The library is called BigNumber , numbers need to be transferred in the form of a line. We use:
    var num = new BigNumber('100000000000000000001');
    num.add(1); // 100000000000000000002
    

    The rest on the library page , there are most of the necessary functions (+ - * /), accept numbers, strings, and the same BigNumber.

    Bigfloat

    There is also a Float, there are also 15 characters there, but the extra digits are simply thrown away.
    >> 3.14159265358979323
      3.141592653589793
    

    You can use the same library in the same format:
    var pi = new BigNumber('3.14159265358979323');
    pi.add('0.00000000000000003'); // 3.14159265358979326
    


    Fraction

    The third type is fractions. The number is rounded. And because of this, the result may go bad.
    >> 1/3
      0.3333333333333333
    >> 1/3 + 2/3
      1
    >> 0.3333333333333333 + 0.6666666666666666
      1
    


    And we have the library Fraction.js .
    var a = new Fraction(1,3);
    a.add( new Fraction(2,3) ); // 1
    

    That's all

    Thanks for attention

    Also popular now: