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 | nulltypescript
import { Decimal } from 'timescope';
const d1 = Decimal(10);
const d2 = Decimal('10.5');
const d3 = Decimal(null); // Returns nullArithmetic Operations
| Property | Type | Description |
|---|---|---|
add(v) | Decimal | Addition |
sub(v) | Decimal | Subtraction |
mul(v) | Decimal | Multiplication |
div(v, digits?) | Decimal | Division with precision |
mod(v) | Decimal | Modulo |
neg() | Decimal | Negation |
abs() | Decimal | Absolute 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) // 1Comparison
| Property | Type | Description |
|---|---|---|
eq(v) | boolean | Equal to |
neq(v) | boolean | Not equal to |
lt(v) | boolean | Less than |
le(v) | boolean | Less than or equal |
gt(v) | boolean | Greater than |
ge(v) | boolean | Greater than or equal |
cmp(v) | number | Compare (-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) // 1Rounding
| Property | Type | Description |
|---|---|---|
round(digits?) | Decimal | Round to nearest |
floor(digits?) | Decimal | Round down |
ceil(digits?) | Decimal | Round up |
trunc(digits?) | Decimal | Truncate |
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.14Conversion
| Property | Type | Description |
|---|---|---|
toString() | string | Convert to string |
toFixed(digits) | string | Format with fixed decimals |
number() | number | Convert to number (may lose precision) |
integer() | bigint | Convert to integer |
typescript
const d = Decimal('3.14159');
d.toString() // '3.14159'
d.toFixed(2) // '3.14'
d.number() // 3.14159
d.integer() // 3nAdvanced
| Property | Type | Description |
|---|---|---|
pow(exp, digits?) | Decimal | Power |
sqrt(digits?) | Decimal | Square root |
root(n, digits?) | Decimal | Nth root |
log(base, digits?) | Decimal | Logarithm |
typescript
const d = Decimal(16);
d.pow(2) // 256
d.sqrt() // 4
d.root(4) // 2
d.log(2) // 4Utilities
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