📖 These are the docs for an older version. View the latest BigDecimal.js documentation →

Function Big

  • Constructor function for BigDecimal. Can be invoked with new or without new.

    The values passed must match one of Java BigDecimal's constructors, so the valid usages of this function is listed below:

    Big(123n); // bigint, 123
    Big(123n, 3); // bigint and scale, 0.123
    Big(123n, 3, MC(2, RoundingMode.HALF_UP)); // bigint, scale and mc, 0.12
    Big(aBigDecimal) // Copies the BigDecimal passed. "scale" and "mc" arguments will not used.
    Big(123n, undefined, MC(2, RoundingMode.HALF_UP)); // bigint and mc, 1.2E+2
    Big('1.13e12'); // string, 1.13E+12
    Big('1.11e11', undefined, MC(2, RoundingMode.HALF_UP)); // string and mc, 1.1E+11
    Big(10000); // number, 10000
    Big(123, 5); // integer and scale, 0.00123
    Big(1.1233, undefined, MC(2, RoundingMode.HALF_UP)); // number and scale, 1.1

    Sample Usage:

    // Single unified constructor for multiple values
    const { Big } = require('bigdecimal.js');

    // Construct from a string and clone it
    const x = Big('1.1111111111111111111111');
    const y = new Big(x); // you can also use 'new'

    const z = x.add(y);
    console.log(z.toString()); // 2.2222222222222222222222

    // You can also construct from a number or BigInt:
    const u = Big(1.1);
    const v = Big(2n);

    console.log(u.toString()); // 1.1
    console.log(v.toString()); // 2

    Parameters

    • n: string | number | bigint | BigDecimal

      Any value to build a BigDecimal from. Types other than Number (as safe integer), BigInt and BigDecimal will be internally converted to string and parsed.

    • Optional scale: number

      Scale to use, by default 0.

    • Optional mc: MathContext

      MathContext object which allows you to set precision and rounding mode.

    Returns BigDecimal

    Throws

    RangeError on following situations:

    • If value is a number:
      • Value is not in the range [-Number.MAX_VALUE, Number.MAX_VALUE]
      • Both a scale and a math context is provided. You can only give one of scale and math context. Passing undefined is same as omitting an argument.
      • If value is a double and scale is given.
    • If value is not a safe integer, a BigInt or a BigDecimal, it will be converted to string. An error will be thrown if the string format is invalid.
    • If value is not a BigInt or number, and scale is given.

Generated using TypeDoc