Ebooks

Big.js tutorial

Big.js tutorial shows how to work with arbitrary precision big decimal arithmetic in JavaScript with Big.js module.

Big.js

Big.js is a small, fast JavaScript library for arbitrary-precision decimal arithmetic.

In this tutorial we work with Big.js in a Node application.

Setting up Big.js

First, we install Big.js.

$ nodejs -v
v9.11.2

We use Node version 9.11.2.

$ npm init

We initiate a new Node application.

$ npm i big.js

We install Big.js with npm i big.js command.

JavaScript Number precision error

In the first example, we show that JavaScript Numbers are not precise for doing arbitrary precision arithmetic.

count_currency.js
var sum = 0;
// two euros fifty-five cents
var amount = 2.55;

for (let i = 0; i < 100000; i++) {

    sum += amount;
}

console.log(sum);

In the example, we add two euros fifty-five cents one hundred thousand times.

$ nodejs numbers.js 
254999.9999995398

We have an error in the calculation.

Big.js example

In the next example we correct the error with Big.js.

big_decimal.js
const Big = require('big.js');

var val = new Big(0.0);
var amount = new Big(2.55);

var sum = val.plus(amount).times(100000);

console.log(sum.toFixed(2));

With Big.js library, the calculation is precise.

const Big = require('big.js');

We load the big.js module.

var val = new Big(0.0);
var amount = new Big(2.55);

We create two big decimal values.

var sum = val.plus(amount).times(100000);

We add the value 100000 times. Note that the big decimal values are immutable, so we generate a new variable.

$ nodejs big_decimal.js 
255000.00

This is the output.

In this tutorial, we have worked with arbitrary precision arithmetic with the Big.js library.

You might also be interested in the following related tutorials: Moment.js tutorial, Reading JSON from URL in JavaScript, JavaScript Snake tutorial, JQuery tutorial, Node Sass tutorial, Lodash tutorial.