bignumber.js
Big Integer Library for Javascript.
Requirement
- node.js
- npm
How to install
Open your terminal and execute the following command
npm install biginteger.js
The name of the repo and npm module are different because the repo name has already been taken in npm registry :(.
Features
Currently, library is capable of handling integers with the following operations.
- Addition
- Substraction
- Multiplication
- Division
- Modulo
- Power function.
The floating point functionality will be added soon.
Usage
Once you install the library you can start using it by importing it through require function.
var BigNumber = BigNumber;
-
Creating an instance of BigNumber:
You can create an instance of BigNumber with new operator by providing initial numbers as a string or another instance of BigNumber object.
var a = "1024" b = a;
-
Adding numbers:
You can add numbers using add method of BigNumber object. The function accepts two parameters, number to be added and the optional 'times'. The optional 'times' parameter is used to add 'number' by one or more times.
var a = "1024" b = "1000"; a; // 2024 a; // 11024 // adding two negative numbers results into an addition. a = "-5"; b = "-5"; a; // -10 a; // -20 // adding one positive and negative number results into a subtraction. a = "-5"; b = "5"; a; // 0 a; // 10
-
Subtracting numbers:
The library provides subtract function to carry out subtraction. The signature of the function is same as add. The sign of the result is properly handled by the function.
var a = "5" b = "1"; a; // 4 a; // -1 // subtracting a positive and a negative number results into an addition. a = "5"; b = "-6"; a; // 11 // if the sign of variable 'a' in the above example is negative, // the resulting operation will be subtraction and the // result will be '1' a = "-5"; b = "-6"; a; // 1
-
Multiplication:
Multiplication of numbers is done through multiply method of BigNumber instance. The function takes same number of parameters as add and subtract.
var a = "8" b = "2"; a; // 16 a; // 64 a = "-4"; b = "8"; a; // -32