big.js

A small, fast, easy-to-use library for arbitrary-precision decimal arithmetic.

Hosted on GitHub.

The library is incorporated into this page, so it should be available in the console now.

API

In all examples below, var and semicolons are not shown, and if a commented-out value is in quotes it means toString has been called on the preceding expression.

CONSTRUCTOR

BigBig(n) ⇒ Big

n : number|string|Big

The argument n must be a decimal value.

Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid.
String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9.

String values may be in exponential, as well as normal (non-exponential) notation.

There is no limit to the number of digits of a string value (other than that of JavaScript's maximum array size), but the largest recommended exponent magnitude is 1000000.

Returns a new Big number object with value n.

Throws on an invalid n.

To create additional Big number constructor functions each with their own separate configuration see below.

x = new Big(9)                       // '9'
y = new Big(x)                       // '9'
Big(435.345)                         // 'new' is optional
new Big('5032485723458348569331745.33434346346912144534543')
new Big('4.321e+4')                  // '43210'
new Big('-735.0918e-430')            // '-7.350918e-428'

Properties

DP

number : integer, 0 to 1e+6 inclusive
Default value: 20

The maximum number of decimal places of the results of operations involving division.
It is relevant only to the div and sqrt methods, and the pow method when the exponent is negative.

The value will be checked for validity when one of the above methods is called.
An error will be thrown if the value is found to be invalid.

Big.DP = 40
RM

number : 0, 1, 2 or 3
Default value: 1

The rounding mode used in the above operations and by round, toExponential, toFixed and toPrecision.

Value Description BigDecimal equivalent
0 Rounds towards zero.
I.e. truncate, no rounding.
ROUND_DOWN
1 Rounds towards nearest neighbour.
If equidistant, rounds away from zero.
ROUND_HALF_UP
2 Rounds towards nearest neighbour.
If equidistant, rounds towards even neighbour.
ROUND_HALF_EVEN
3 Rounds away from zero. ROUND_UP

The value will be checked for validity when one of the above methods is called.
An error will be thrown if the value is found to be invalid.

Big.RM = 0
NE

number : integer, -1e+6 to 0 inclusive
Default value: -7

The negative exponent value at and below which toString returns exponential notation.

Big.NE = -7
x = new Big(0.00000123)            // '0.00000123'       e is -6
x = new Big(0.000000123)           // '1.23e-7'

JavaScript numbers use exponential notation for negative exponents of -7 and below.

Regardless of the value of Big.NE, the toFixed method will always return a value in normal notation and the toExponential method will always return a value in exponential form.

PE

number : integer, 0 to 1e+6 inclusive
Default value: 21

The positive exponent value at and above which toString returns exponential notation.

Big.PE = 2
x = new Big(12.3)                  // '12.3'        e is 1
x = new Big(123)                   // '1.23e+2'

JavaScript numbers use exponential notation for positive exponents of 21 and above.

Regardless of the value of Big.PE, the toFixed method will always return a value in normal notation and the toExponential method will always return a value in exponential form.

INSTANCE

Methods

The methods inherited by a Big number instance from its constructor's prototype object.

A Big number is immutable in the sense that it is not changed by its methods.

abs.abs() ⇒ Big

Returns a Big number whose value is the absolute value, i.e. the magnitude, of this Big number.

x = new Big(-0.8)
x.abs()                     // '0.8'
cmp.cmp(n) ⇒ number

n : number|string|Big

Returns  
1 If the value of this Big number is greater than the value of n
-1 If the value of this Big number is less than the value of n
0 If this Big number and n have the same value

Throws if n is invalid.

x = new Big(6)
y = new Big(5)
x.cmp(y)                   // 1
y.cmp(x.minus(1))          // 0
div.div(n) ⇒ Big

n : number|string|Big

Returns a Big number whose value is the value of this Big number divided by n.

If the result has more fraction digits than is specified by Big.DP, it will be rounded to Big.DP decimal places using rounding mode Big.RM.

Throws if n is zero or otherwise invalid.

x = new Big(355)
y = new Big(113)
x.div(y)                   // '3.14159292035398230088'
Big.DP = 2
x.div(y)                   // '3.14'
x.div(5)                   // '71'
eq.eq(n) ⇒ boolean

n : number|string|Big

Returns true if the value of this Big equals the value of n, otherwise returns false.

Throws if n is invalid.

0 === 1e-324               // true
x = new Big(0)
x.eq('1e-324')             // false
Big(-0).eq(x)              // true  ( -0 === 0 )
gt.gt(n) ⇒ boolean

n : number|string|Big

Returns true if the value of this Big is greater than the value of n, otherwise returns false.

Throws if n is invalid.

0.1 > 0.3 - 0.2              // true
x = new Big(0.1)
x.gt(Big(0.3).minus(0.2))    // false
Big(0).gt(x)                 // false
gte.gte(n) ⇒ boolean

n : number|string|Big

Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false.

Throws if n is invalid.

0.3 - 0.2 >= 0.1               // false
x = new Big(0.3).minus(0.2)
x.gte(0.1)                     // true
Big(1).gte(x)                  // true
lt.lt(n) ⇒ boolean

n : number|string|Big

Returns true if the value of this Big is less than the value of n, otherwise returns false.

Throws if n is invalid.

0.3 - 0.2 < 0.1                // true
x = new Big(0.3).minus(0.2)
x.lt(0.1)                      // false
Big(0).lt(x)                   // true
lte.lte(n) ⇒ boolean

n : number|string|Big

Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false.

Throws if n is invalid.

0.1 <= 0.3 - 0.2               // false
x = new Big(0.1)
x.lte(Big(0.3).minus(0.2))     // true
Big(-1).lte(x)                 // true
minus.minus(n) ⇒ Big

n : number|string|Big

Returns a Big number whose value is the value of this Big number minus n.

Throws if n is invalid.

0.3 - 0.1                  // 0.19999999999999998
x = new Big(0.3)
x.minus(0.1)               // '0.2'
mod.mod(n) ⇒ Big

n : number|string|Big

Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n.

The result will have the same sign as this Big number, and it will match that of JavaScript's % operator (within the limits of its precision) and BigDecimal's remainder method.

Throws if n is negative or otherwise invalid.

1 % 0.9                    // 0.09999999999999998
x = new Big(1)
x.mod(0.9)                 // '0.1'
plus.plus(n) ⇒ Big

n : number|string|Big

Returns a Big number whose value is the value of this Big number plus n.

Throws if n is invalid.

0.1 + 0.2                  // 0.30000000000000004
x = new Big(0.1)
y = x.plus(0.2)            // '0.3'
Big(0.7).plus(x).plus(y)   // '1.1'
pow.pow(n) ⇒ Big

n : number : integer, -1e+6 to 1e+6 inclusive

Returns a Big number whose value is the value of this Big number raised to the power n.

Here, n must be a JavaScript number, not a Big number, because only small integers are allowed.

If n is negative and the result has more fraction digits than is specified by Big.DP, it will be rounded to Big.DP decimal places using rounding mode Big.RM.

Throws if n is invalid.

Note: High value exponents may cause this method to be slow to return.

Math.pow(0.7, 2)           // 0.48999999999999994
x = new Big(0.7)
x.pow(2)                   // '0.49'
Big.DP = 20
Big(3).pow(-2)             // '0.11111111111111111111'

new Big(123.456).pow(1000).toString().length     // 5099
new Big(2).pow(1e+6)       // Time taken (Node.js): 9 minutes 34 secs.
round.round(dp, rm) ⇒ Big

dp? : number : integer, 0 to 1e+6 inclusive
rm? : number : 0, 1, 2 or 3

Returns a Big number whose value is the value of this Big number rounded using rounding mode rm to a maximum of dp decimal places.

if dp is omitted or is undefined, the return value is n rounded to a whole number.
if rm is omitted or is undefined, the current Big.RM setting is used.

Throws if dp or rm is invalid.

x = 123.45
Math.round(x)              // 123
y = new Big(x)
y.round()                  // '123'
y.round(2)                 // '123.45'
y.round(10)                // '123.45'
y.round(1, 0)              // '123.4'
y.round(1, 1)              // '123.5'
y.round(1, 2)              // '123.4'
y.round(1, 3)              // '123.5'
y                          // '123.45'
sqrt.sqrt() ⇒ Big

Returns a Big number whose value is the square root of this Big number.

If the result has more fraction digits than is specified by Big.DP, it will be rounded to Big.DP decimal places using rounding mode Big.RM.

Throws if this Big number is negative.

x = new Big(16)
x.sqrt()                   // '4'
y = new Big(3)
y.sqrt()                   // '1.73205080756887729353'
times.times(n) ⇒ Big

n : number|string|Big

Returns a Big number whose value is the value of this Big number times n.

Throws if n is invalid.

0.6 * 3                    // 1.7999999999999998
x = new Big(0.6)
y = x.times(3)             // '1.8'
Big('7e+500').times(y)     // '1.26e+501'
toExponential.toExponential(dp) ⇒ string

dp? : number : integer, 0 to 1e+6 inclusive

Returns a string representing the value of this Big number in exponential notation to a fixed number of decimal places dp.

If the value of this Big number in exponential notation has more digits to the right of the decimal point than is specified by dp, the return value will be rounded to dp decimal places using rounding mode Big.RM.

If the value of this Big number in exponential notation has fewer digits to the right of the decimal point than is specified by dp, the return value will be appended with zeros accordingly.

If dp is omitted or is undefined, the number of digits after the decimal point defaults to the minimum number of digits necessary to represent the value exactly.

Throws if dp is invalid.

x = 45.6
y = new Big(x)
x.toExponential()          // '4.56e+1'
y.toExponential()          // '4.56e+1'
x.toExponential(0)         // '5e+1'
y.toExponential(0)         // '5e+1'
x.toExponential(1)         // '4.6e+1'
y.toExponential(1)         // '4.6e+1'
x.toExponential(3)         // '4.560e+1'
y.toExponential(3)         // '4.560e+1'
toFixed.toFixed(dp) ⇒ string

dp? : number : integer, 0 to 1e+6 inclusive

Returns a string representing the value of this Big number in normal notation to a fixed number of decimal places dp.

If the value of this Big number in normal notation has more digits to the right of the decimal point than is specified by dp, the return value will be rounded to dp decimal places using rounding mode Big.RM.

If the value of this Big number in normal notation has fewer fraction digits then is specified by dp, the return value will be appended with zeros accordingly.

Unlike Number.prototype.toFixed, which returns exponential notation if a number is greater or equal to 1021, this method will always return normal notation.

If dp is omitted or is undefined, the return value is simply the value in normal notation. This is also unlike Number.prototype.toFixed, which returns the value to zero decimal places.

Throws if dp is invalid.

x = 45.6
y = new Big(x)
x.toFixed()                // '46'
y.toFixed()                // '45.6'
y.toFixed(0)               // '46'
x.toFixed(3)               // '45.600'
y.toFixed(3)               // '45.600'
toPrecision.toPrecision(sd) ⇒ string

sd? : number : integer, 1 to 1e+6 inclusive

Returns a string representing the value of this Big number to the specified number of significant digits sd.

If the value of this Big number has more digits than is specified by sd, the return value will be rounded to sd significant digits using rounding mode Big.RM.

If the value of this Big number has fewer digits than is specified by sd, the return value will be appended with zeros accordingly.

If sd is less than the number of digits necessary to represent the integer part of the value in normal notation, exponential notation is used.

If sd is omitted or is undefined, the return value is the same as .toString().

Throws if sd is invalid.

x = 45.6
y = new Big(x)
x.toPrecision()            // '45.6'
y.toPrecision()            // '45.6'
x.toPrecision(1)           // '5e+1'
y.toPrecision(1)           // '5e+1'
x.toPrecision(5)           // '45.600'
y.toPrecision(5)           // '45.600'
toString.toString() ⇒ string

Returns a string representing the value of this Big number.

If this Big number has a positive exponent that is equal to or greater than 21, or a negative exponent equal to or less than -7, exponential notation is returned.

The point at which toString returns exponential rather than normal notation can be adjusted by changing the value of Big.PE and Big.NE. By default, Big numbers correspond to JavaScript's number type in this regard.

x = new Big('9.99e+20')
x.toString()               // '999000000000000000000'
y = new Big('1E21')
y.toString()               // '1e+21'
valueOf.valueOf() ⇒ string

As toString except the minus sign is included for negative zero.

x = new Big(-0)
x.valueOf()                // '-0'
x.toString()                // '0'
toJSON.toJSON() ⇒ string

As valueOf.

x = new Big('177.7e+457')
y = new Big(235.4325)
z = new Big('0.0098074')
str = JSON.stringify( [x, y, z] )

JSON.parse(str, function (k, v) { return k === '' ? v : new Big(v) })
// Returns an array of three Big numbers.

Properties

A Big number is an object with three properties:

Property Description Type Value
c coefficient* number[] Array of single digits
e exponent number Integer, -1e+6 to 1e+6 inclusive
s sign number -1 or 1

*significand

The value of a Big number is stored in a normalised decimal floating point format which corresponds to the value's toExponential form, with the decimal point to be positioned after the most significant (left-most) digit of the coefficient.

Note that, as with JavaScript numbers, the original exponent and fractional trailing zeros are not preserved.

x = new Big(0.123)                 // '0.123'
x.toExponential()                  // '1.23e-1'
x.c                                // '1,2,3'
x.e                                // -1
x.s                                // 1

y = new Number(-123.4567000e+2)    // '-12345.67'
y.toExponential()                  // '-1.234567e+4'
z = new Big('-123.4567000e+2')     // '-12345.67'
z.toExponential()                  // '-1.234567e+4'
z.c                                // '1,2,3,4,5,6,7'
z.e                                // 4
z.s                                // -1

A Big number is mutable in the sense that the value of its properties can be changed.
For example, to rapidly shift a value by a power of 10:

x = new Big('1234.000')    // '1234'
x.toExponential()          // '1.234e+3'
x.c                        // '1,2,3,4'
x.e                        // 3

x.e = -5
x                          // '0.00001234'

If changing the coefficient array directly, which is not recommended, be careful to avoid leading or trailing zeros (unless zero itself is being represented).

Minus zero is a valid Big number value, but like JavaScript numbers the minus sign is not shown by toString.

x = new Number(-0)         // 0
1 / x == -Infinity         // true

y = new Big(-0)            // '0'
y.c                        // '0'    [0].toString()
y.e                        // 0
y.s                        // -1

Errors

The errors that are thrown are instances of Error.
The message of the errors always begins with [big.js], for example:

Error: [big.js] Invalid number
Method(s) Error message Thrown on
Big
cmp
div
eq gt gte lt lte
minus
mod
plus
times
Invalid number Invalid number
div Division by zero Division by zero
Invalid decimal places Invalid Big.DP
Invalid rounding mode Invalid Big.RM
mod Division by zero Modulo zero
pow Invalid exponent Invalid exponent
Invalid decimal places Invalid Big.DP
Invalid rounding mode Invalid Big.RM
round Invalid decimal places Invalid dp
Invalid rounding mode Invalid rm/Big.RM
sqrt No square root Negative number
Invalid decimal places Invalid Big.DP
Invalid rounding mode Invalid Big.RM
toExponential Invalid decimal places Invalid dp
Invalid rounding mode Invalid Big.RM
toFixed Invalid decimal places Invalid dp
Invalid rounding mode Invalid Big.RM
toPrecision Invalid precision Invalid sd
Invalid rounding mode Invalid Big.RM

FAQ

How can I convert a Big number to a primitive JavaScript number?

To convert a Big number to a primitive number, parseFloat or any of the other methods for converting a string to a number can be used.

x = new Big('12345.6789')
parseFloat(x)             // 12345.6789
Number(x)                 // 12345.6789
+x                        // 12345.6789
x * 1                     // 12345.6789
x / 1                     // 12345.6789
x - 0                     // 12345.6789
x + 0                     // '12345.67890' (string concatenation, do not use!)

If converting to an integer be aware that parseInt doees not handle exponential notation.

x = new Big('9.87654e+32')
parseInt(x)               // 9
parseInt(+x)              // 9
parseInt(x.toFixed())     // 9.87654e+32
parseInt(x.round())       // 9.87654e+32

The Math methods can also be used.

x = new Big('1234.56')
Math.floor(x)             // 1234
Math.round(x)             // 1235

How can I round a Big number to a specified number of significant digits?

toPrecision returns a string representing the value of a Big number rounded to a specified number of significant digits. Or, the number of significant digits of a Big number can be set by truncating the array that stores its coefficient. For example, using the array's length property:

x = new Big('987.654321')
len = x.c.length          // 9
if (len > 6) x.c.length = 6
x                         // 987.654

How can I set the decimal places and/or rounding mode for just one operation?

This library uses a global configuration for the decimal places and rounding mode used by division operations, so it is just a matter of altering this as required.

Big.DP = 10
y = x.sqrt()
Big.DP = 0
Big.RM = 1
z = x.div(3)

There is also the ability to create separate Big number constructors each with their own particular DP and RM settings. See below.

Finally, there is the option of redefining the relevant prototype method as required. For example, the following would enable a decimal places and rounding mode to be passed to the div method.

Big.prototype.div = (function () {
  var div = Big.prototype.div;
  return function (n, dp, rm) {
    var result,
      Big = this.constructor,
      DP = Big.DP,
      RM = Big.RM;
    if (dp != undefined) Big.DP = dp;
    if (rm != undefined) Big.RM = rm;
    result = div.call(this, n);
    Big.DP = DP;
    Big.RM = RM;
    return result;
  }
})();

var dp = 10;
var round_up = 2;
x = x.div(y, dp, round_up);

How can I simultaneously use different decimal places and/or rounding mode settings for different Big numbers?

From v3.0.0, it is possible to have multiple Big number constructors each with their own particular DP and RM settings which apply to all Big numbers created from it.

As shown below, an additional Big number constructor is created by calling an existing Big number constructor without using new and without any argument.

Big10 = Big();

Big.DP = 3;
Big10.DP = 10;

x = Big(5);
y = Big10(5);

x.div(3)     // 1.667
y.div(3)     // 1.6666666667

Big numbers created by different constructors can be used together in operations, and it is the DP and RM setting of the Big number that an operation is called upon that will apply.

In the interest of memory efficiency, all Big number constructors share the same prototype object, so while the DP and RM (and any other own properties) of a constructor are isolated and untouchable by another, its prototype methods are not.


Why are trailing fractional zeros removed from Big numbers?

Many arbitrary-precision libraries retain trailing fractional zeros as they can indicate the precision of a value. This can be useful but the results of arithmetic operations can be misleading.

x = new BigDecimal("1.0")
y = new BigDecimal("1.1000")
z = x.add(y)                      // 2.1000

x = new BigDecimal("1.20")
y = new BigDecimal("3.45000")
z = x.multiply(y)                 // 4.1400000

To specify the precision of a value is to imply that the value lies within a certain range.

In the first example, x has a value of 1.0. The trailing zero shows the precision of the value, implying that the value is in the range 0.95 to 1.05. Similarly, the precision indicated by the trailing zeros of y indicates that the value is in the range 1.09995 to 1.10005. If we add the two lowest values in the ranges we get 0.95 + 1.09995 = 2.04995 and if we add the two highest values we get 1.05 + 1.10005 = 2.15005, so the range of the result of the addition implied by the precision of its operands is 2.04995 to 2.15005. The result given by BigDecimal of 2.1000 however, indicates that the value is in the range 2.09995 to 2.10005 and therefore the precision implied by its trailing zeros is misleading.

In the second example, the true range is 4.122744 to 4.157256 yet the BigDecimal answer of 4.1400000 indicates a range of 4.13999995 to 4.14000005. Again, the precision implied by the trailing zeros is misleading.

This library, like binary floating-point and most calculators, does not retain trailing fractional zeros.
Instead, the toExponential, toFixed and toPrecision methods enable trailing zeros to be added if and when required.