4.1.0 • Published 8 years ago

linear-arbitrary-precision v4.1.0

Weekly downloads
6
License
MIT
Repository
github
Last release
8 years ago

linear-arbitrary-precision

Build Status Coverage Status Code Climate

Abstraction for linear functionality in big.js, bignumber.js, decimal.js and others via adapters.

Install

npm i linear-arbitrary-precision

Usage

See CodePen example

Adapters

See up to date list.

Factory and configuration

var decimalFactory = require('linear-arbitrary-precision');
var adapter = require('bigjs-adapter'); // See adapters section for full list

var Decimal = decimalFactory(adapter);

Decimal.getPrecision(); // => 20

new Decimal('1').div(new Decimal('3')).valueOf(); // => '0.33333333333333333333'

Decimal.setPrecision(5);

new Decimal('1').div(new Decimal('3')).valueOf(); // => '0.33333'

Operations

new Decimal('0.1').plus(new Decimal('0.2')).valueOf(); // => '0.3'
new Decimal('0.3').minus(new Decimal('0.1')).valueOf(); // => '0.2'
new Decimal('0.6').times(new Decimal('3')).valueOf(); // => '1.8'
new Decimal('0.3').div(new Decimal('0.2')).valueOf(); // => '1.5'

new Decimal('1').equals(new Decimal('1')); // => true
new Decimal('1').equals(new Decimal('2')); // => false

toString, valueOf and toJSON

var decimalThird = new Decimal('1').div(new Decimal('3'));

// with bigjs-adapter (other adapters might have differing implementations)
decimalThird.toString() === decimalThird.valueOf() === decimalThird.toJSON(); // => true

Number(decimalThird); // => 1/3

JSON.stringify and JSON.parse with reviver

var Decimal40 = decimalFactory(adapter);

Decimal40.setPrecision(40);

var decimalThird = new Decimal40('1').div(new Decimal('3'));

var stringified = JSON.stringify(decimalThird);
// => '"0.3333333333333333333333333333333333333333"'

JSON.parse(stringified, Decimal40.reviver);
// => new Decimal40('0.3333333333333333333333333333333333333333')

See spec.

Related projects