Skip to content

Class: MathContext

Defined in: bigdecimal.ts:164

Immutable objects which encapsulate the context settings which describe certain rules for numerical operators, such as those implemented by the BigDecimal class.

The base-independent settings are:

  • precision: the number of digits to be used for an operation; results are rounded to this precision
  • roundingMode: a RoundingMode object which specifies the algorithm to be used for rounding.

Sample Usage:

javascript
const { Big, MC, RoundingMode } = require('bigdecimal.js');

const x = Big('1');
const y = Big('3');

const res1 = x.divideWithMathContext(y, new MC(3));
console.log(res1.toString()); // 0.333

// You can also use without `new` operator
const res2 = x.divideWithMathContext(y, MC(3, RoundingMode.UP));
console.log(res2.toString()); // 0.334

try {
    x.divide(y);
    // throws since full precision is requested but it is not possible
} catch (e) {
    console.log(e); // RangeError: Non-terminating decimal expansion; no exact representable decimal result.
}

Constructors

Constructor

ts
new MathContext(precision, roundingMode?): MathContext;

Defined in: bigdecimal.ts:181

Parameters

precision

number

roundingMode?

RoundingMode = MathContext.DEFAULT_ROUNDINGMODE

Returns

MathContext

Properties

precision

ts
readonly precision: number;

Defined in: bigdecimal.ts:173

The number of digits to be used for an operation. A value of 0 indicates that unlimited precision (as many digits as are required) will be used. Note that leading zeros (in the coefficient of a number) are never significant.

precision will always be non-negative.


roundingMode

ts
readonly roundingMode: RoundingMode;

Defined in: bigdecimal.ts:179

The rounding algorithm to be used for an operation. By default it is HALF_UP.

see RoundingMode


DECIMAL128

ts
static DECIMAL128: MathContext;

Defined in: bigdecimal.ts:222

A MathContext object with a precision setting matching the precision of the IEEE 754-2019 decimal128 format, 34 digits, and a rounding mode of HALF_EVEN. Note the exponent range of decimal64 is not used for rounding.


DECIMAL32

ts
static DECIMAL32: MathContext;

Defined in: bigdecimal.ts:206

A MathContext object with a precision setting matching the precision of the IEEE 754-2019 decimal32 format, 7 digits, and a rounding mode of HALF_EVEN. Note the exponent range of decimal32 is not used for rounding.


DECIMAL64

ts
static DECIMAL64: MathContext;

Defined in: bigdecimal.ts:214

A MathContext object with a precision setting matching the precision of the IEEE 754-2019 decimal64 format, 16 digits, and a rounding mode of HALF_EVEN. Note the exponent range of decimal64 is not used for rounding.


UNLIMITED

ts
static UNLIMITED: MathContext;

Defined in: bigdecimal.ts:198

A MathContext object whose settings have the values required for unlimited precision arithmetic. The values of the settings are: precision=0 roundingMode=HALF_UP

Released under the Apache-2.0 License.