📜 ⬆️ ⬇️

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

In JavaScript, there is one type of number by default - Number. Although it is of course divided into Int and Float, although this is expressed in a few (for example, in the functions parseInt - 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. At the same time, in Int the remaining digits are stored as zeros. Example:
>> 100000000000000000111 100000000000000000000 

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

The rest of 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, but the extra numbers 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 can be spoiled.
 >> 1/3 0.3333333333333333 >> 1/3 + 2/3 1 >> 0.3333333333333333 + 0.6666666666666666 1 

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

That's all

Thanks for attention

Source: https://habr.com/ru/post/147037/


All Articles