big.js

repository·main·Indexed 26 days ago

https://github.com/mikemcl/big.js

A small, fast, and easy-to-use JavaScript library for arbitrary-precision decimal arithmetic. It provides a Big constructor for creating immutable decimal numbers and supports standard arithmetic operations (plus, minus, times, div, pow, sqrt, mod), comparisons, and formatting methods like toFixed and toPrecision. The library includes configurable global defaults for decimal places (Big.DP), rounding modes (Big.RM), and a strict mode to prevent precision loss.

Tokens
2.3K
Snippets
8
Records
18
Agent score
90%

What's inside big.js

  1. Run performance benchmarks with bigtime.js

    main

    The bigtime.js application is a Node.js command-line tool used to test big.js against the GWT version of BigDecimal from the npm registry.

    To run a benchmark, use the following syntax: node bigtime <method> <iterations> <digits>

    This will execute the specified number of calls to the given method using operands with up to the specified number of random digits, and verify that the results match.

  2. Install big.js

    main

    You can install big.js for various environments:

    Node.js

    Install via npm:

    $ npm install big.js

    Use with CommonJS:

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

    Use with ES modules:

    import Big from 'big.js';

    Deno

    Import directly from a URL:

    import Big from 'https://raw.githubusercontent.com/mikemcl/big.js/v7.0.1/big.mjs';
    // or
    import Big from 'https://unpkg.com/big.js@latest/big.mjs';

    Browsers

    Add to global scope via script tag:

    <script src='path/to/big.js'></script>

    Use as an ES module:

    <script type='module'>
    import Big from './path/to/big.mjs';
    </script>

    Use a minified version from a CDN:

    <script src='https://cdn.jsdelivr.net/npm/big.js@7.0.1/big.min.js'></script>
    $ npm install big.js
  3. Run performance benchmarks with big-vs-bigdecimal.html

    main
    To compare the performance of big.js against JavaScript implementations of Java's BigDecimal in a browser environment, open the big-vs-bigdecimal.html file directly in any web browser.
  4. Perform arithmetic with Big numbers

    main

    Big numbers are immutable; methods return a new Big number rather than modifying the original. Methods can be chained for complex calculations.

    Note: Arithmetic methods return exact results except for div, sqrt, and pow (with negative exponent), which involve division. The precision and rounding for these methods are controlled by the Big.DP (decimal places) and Big.RM (rounding mode) properties of the constructor.

    x = new Big(0.3)
    x.minus(0.1) // "0.2"
    
    // Chaining
    x.div(y).plus(z).times(9)
    
    // Configuring precision
    Big.DP = 10
    Big.RM = Big.roundHalfUp
    x.div(y) // result rounded to 10 decimal places
    x.div(y).plus(z).times(9).minus('1.234567801234567e+8').plus(976.54321).div('2598.11772')
  5. Configure Big strict mode

    main

    When Big.strict is set to true, creating a Big number from a primitive number is disallowed to prevent precision issues. This will throw a TypeError.

    Big.strict = true
    x = new Big(1) // TypeError: [big.js] Invalid number
    Big.strict = true
    x = new Big(1) // TypeError: [big.js] Invalid number
  6. Access Big number internal components

    main

    A Big number's value is stored in a decimal floating point format consisting of a coefficient, exponent, and sign.

    • x.c: coefficient (significand)
    • x.e: exponent
    • x.s: sign
    x = new Big(-123.456)
    x.c // [1,2,3,4,5,6]
    x.e // 2
    x.s // -1
    x = new Big(-123.456);
    x.c                                    // [1,2,3,4,5,6]    coefficient (i.e. significand)
    x.e                                    // 2                exponent
    x.s                                    // -1               sign
  7. Use the Big constructor

    main

    The library exports a single constructor function, Big. You can create a Big number from a primitive number, string, or another Big number. Note that the new keyword is optional.

    x = new Big(123.4567)
    y = Big('123456.7e-3')
    z = new Big(x)
    x = new Big(123.4567)
    y = Big('123456.7e-3')
    z = new Big(x)
  8. Format Big numbers with toExponential, toFixed, and toPrecision

    main

    big.js replicates the standard JavaScript Number methods for formatting: toExponential, toFixed, and toPrecision.

    x = new Big(255.5)
    x.toExponential(5) // "2.55500e+2"
    x.toFixed(5)       // "255.50000"
    x.toPrecision(5)   // "255.50"
    x = new Big(255.5)
    x.toExponential(5)                     // "2.55500e+2"
    x.toFixed(5)                           // "255.50000"
    x.toPrecision(5)                       // "255.50"
  9. Configure Big global defaults

    main

    You can modify the global behavior of all Big instances by setting properties on the Big constructor.

    Rounding Modes (Big.RM):

    • 0 (Big.roundDown): Towards zero (truncate).
    • 1 (Big.roundHalfUp): To nearest neighbour. If equidistant, round up.
    • 2 (Big.roundHalfEven): To nearest neighbour. If equidistant, to even.
    • 3 (Big.roundUp): Away from zero.

    Global Properties:

    • Big.DP: The default maximum number of decimal places for division, sqrt, and pow with negative exponents (Default: 20).
    • Big.RM: The default rounding mode (Default: 1).
    • Big.strict: If true, an error is thrown if a primitive number is passed to the constructor, or if valueOf or toNumber is called on a Big that cannot be converted without loss of precision (Default: false).
    • Big.NE: The negative exponent at and beneath which toString returns exponential notation (Default: -7).
    • Big.PE: The positive exponent at and above which toString returns exponential notation (Default: 21).
  10. Format Big values as strings

    main

    Use these methods to convert a Big instance into a string representation.

    • toString() / toJSON(): Returns the value in normal or exponential notation based on Big.NE and Big.PE.
    • toFixed(dp, rm?): Returns a string in normal notation with exactly dp decimal places. Uses Big.RM if rm is not provided.
    • toExponential(dp, rm?): Returns a string in exponential notation with dp decimal places.
    • toPrecision(sd, rm?): Returns a string rounded to sd significant digits.
    • valueOf(): Returns a string representation (Note: if Big.strict is true, this throws an error).