UtilAdded in v15.5Optional

wrDecimal

Exact decimal arithmetic on strings, with no float on the way. Built on BigInt, no dependency.

Installation

Import the class, and @use the entry point in your global styles. Nothing warns you when the @use is missing.

import { Component } from '@angular/core';
import { WrInputNumber } from 'ngwr/input-number';
import { wrDecimalAdd } from 'ngwr/utils';

@Component({ imports: [WrInputNumber] })
export class MyComponent {}

Usage

A decimal is a string: '0.1', '-1234.56'. Every helper reads a string, a number or a bigint, and returns the canonical string, or null when a side is not a number. Nothing throws. wr-table summaries and wr-input-number in mode="decimal" run on the same core.

import { wrDecimal, wrDecimalAdd, wrDecimalDivide, wrDecimalRound } from 'ngwr/utils';

wrDecimalAdd('0.1', '0.2');            // '0.3'
wrDecimalAdd('9007199254740993.01', 1); // '9007199254740994.01'
wrDecimalDivide('10', 3, 2);           // '3.33'
wrDecimalRound('1.005', 2);            // '1.01'
wrDecimal('abc');                      // null

wrDecimalAdd of the two: 0.3

+ on doubles: 0.30000000000000004

Rules

InputResult
'00.10', ' -5. ', '.5' Canonical: '0.10', '-5', '0.5'. Trailing fraction zeros stay.
'9007199254740993.01'Every digit kept. A number is read from its shortest form: 0.1 is '0.1'.
'1e5', '1.5E-3'Read exactly: '100000', '0.0015'. An exponent past 1000 is malformed.
'', 'abc', '1.2.3', '1,5', 'Infinity', NaN, nullMalformed: null. Never zero, never a throw.
Scale of a sumThe wider of the two: '10.00' + '0.5' is '10.50'.
Rounding Half away from zero: '2.5' to '3', '-2.5' to '-3'.

API

NameDescriptionTypeDefault
wrDecimalReads a value as an exact decimal and returns the canonical string, or null when it is not a number.(value: unknown) => string | null-
wrDecimalAdda + b at the wider scale of the two.(a: WrDecimalLike, b: WrDecimalLike) => string | null-
wrDecimalSubtracta - b at the wider scale of the two.(a: WrDecimalLike, b: WrDecimalLike) => string | null-
wrDecimalMultiplya * b; the scales add.(a: WrDecimalLike, b: WrDecimalLike) => string | null-
wrDecimalDividea / b at exactly decimals places, half away from zero. null for a zero divisor.(a: WrDecimalLike, b: WrDecimalLike, decimals: number) => string | null-
wrDecimalCompareOrders two decimals by value: -1, 0 or 1. 1.50 and 1.5 are equal.(a: WrDecimalLike, b: WrDecimalLike) => -1 | 0 | 1 | null-
wrDecimalRoundSets the scale to exactly decimals places: pads with zeros or rounds half away from zero.(value: WrDecimalLike, decimals: number) => string | null-
WrDecimalLikeWhat the helpers read. null and undefined read as malformed, so data can be passed straight in.string | number | bigint | null | undefined-

See also