Skip to content

Decimal

Arbitrary-precision decimal arithmetic type.

Overview

Timescope uses Decimal for representing time values, data values, and resolutions with arbitrary precision. This avoids floating-point arithmetic errors.

The timescope package re-exports Decimal.

Constructor

typescript
Decimal(value: DecimalLike): Decimal
Decimal(value: undefined | null): undefined | null
typescript
import { Decimal } from 'timescope';

const d1 = Decimal(10);
const d2 = Decimal('10.5');
const d3 = Decimal(null);  // Returns null

Arithmetic Operations

PropertyTypeDescription
add(v)DecimalAddition
sub(v)DecimalSubtraction
mul(v)DecimalMultiplication
div(v, digits?)DecimalDivision with precision
mod(v)DecimalModulo
neg()DecimalNegation
abs()DecimalAbsolute value
typescript
const a = Decimal(10);
const b = Decimal(3);

a.add(b)      // 13
a.sub(b)      // 7
a.mul(b)      // 30
a.div(b, 2)   // 3.33 (2 decimal places)
a.mod(b)      // 1

Comparison

PropertyTypeDescription
eq(v)booleanEqual to
neq(v)booleanNot equal to
lt(v)booleanLess than
le(v)booleanLess than or equal
gt(v)booleanGreater than
ge(v)booleanGreater than or equal
cmp(v)numberCompare (-1, 0, 1)
typescript
const a = Decimal(10);
const b = Decimal(5);

a.gt(b)   // true
a.le(b)   // false
a.eq(10)  // true
a.cmp(b)  // 1

Rounding

PropertyTypeDescription
round(digits?)DecimalRound to nearest
floor(digits?)DecimalRound down
ceil(digits?)DecimalRound up
trunc(digits?)DecimalTruncate
typescript
const d = Decimal('3.14159');

d.round(2)  // 3.14
d.floor(2)  // 3.14
d.ceil(2)   // 3.15
d.trunc(2)  // 3.14

Conversion

PropertyTypeDescription
toString()stringConvert to string
toFixed(digits)stringFormat with fixed decimals
number()numberConvert to number (may lose precision)
integer()bigintConvert to integer
typescript
const d = Decimal('3.14159');

d.toString()    // '3.14159'
d.toFixed(2)    // '3.14'
d.number()      // 3.14159
d.integer()     // 3n

Advanced

PropertyTypeDescription
pow(exp, digits?)DecimalPower
sqrt(digits?)DecimalSquare root
root(n, digits?)DecimalNth root
log(base, digits?)DecimalLogarithm
typescript
const d = Decimal(16);

d.pow(2)       // 256
d.sqrt()       // 4
d.root(4)      // 2
d.log(2)       // 4

Utilities

typescript
Decimal.isDecimal(v)      // Check if value is Decimal
Decimal.pow10(n)          // 10^n as Decimal
Decimal.min(...values)    // Minimum value
Decimal.max(...values)    // Maximum value
Decimal.minmax(...values) // [min, max]

Examples

Precision Arithmetic

typescript
const a = Decimal('0.1');
const b = Decimal('0.2');

// Decimal arithmetic
a.add(b).eq('0.3')  // true

// JavaScript floating-point arithmetic
0.1 + 0.2 === 0.3   // false

See Also