CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-decimal-js-light

An arbitrary-precision Decimal type for JavaScript

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Decimal.js-light

Decimal.js-light is a lightweight arbitrary-precision decimal arithmetic library for JavaScript. It's a smaller alternative to decimal.js with reduced functionality but significantly smaller bundle size (12.7 KB vs 32.1 KB minified). It provides high-precision decimal calculations essential for financial computations, scientific calculations, and any scenario requiring exact decimal arithmetic without floating-point precision errors.

Package Information

  • Package Name: decimal.js-light
  • Package Type: npm
  • Language: JavaScript (with TypeScript definitions)
  • Installation: npm install decimal.js-light

Core Imports

import Decimal from "decimal.js-light";

ES Modules:

import Decimal from "decimal.js-light";

CommonJS:

const Decimal = require("decimal.js-light");

Browser (UMD):

<script src="decimal.js"></script>
<!-- Decimal is now available as a global -->

Basic Usage

import Decimal from "decimal.js-light";

// Create decimal numbers from strings for precision
const a = new Decimal("123.456789");
const b = new Decimal("987.654321");

// Perform precise arithmetic operations
const sum = a.plus(b);              // Addition
const product = a.times(b);         // Multiplication
const quotient = a.dividedBy(b);    // Division

// Chain operations
const result = new Decimal("10")
  .plus("5")
  .times("2")
  .dividedBy("3");

console.log(result.toString()); // "10"

Architecture

Decimal.js-light is built around the core Decimal class with these key characteristics:

  • Immutable Operations: All arithmetic operations return new Decimal instances
  • Truncation by Default: Arithmetic operations truncate rather than round by default
  • Configurable Precision: Global configuration for precision and rounding modes
  • Method Aliases: Most methods have shorter aliases (e.g., plus/add, absoluteValue/abs)
  • Base 10 Focus: Only handles base 10 numbers (no binary/hex support)
  • No Special Values: Doesn't handle NaN, Infinity, or negative zero

Capabilities

Decimal Constructor

Creates a new Decimal instance from a numeric value.

/**
 * Creates a new Decimal instance
 * @param value - A numeric value (string, number, or Decimal)
 */
class Decimal {
  constructor(value: Numeric);
}

type Numeric = string | number | Decimal;

Arithmetic Operations

Core mathematical operations with precise decimal arithmetic.

/**
 * Addition - returns this + y, truncated to precision
 * @param y - Value to add
 */
plus(y: Numeric): Decimal;
add(y: Numeric): Decimal;  // Alias for plus

/**
 * Subtraction - returns this - y, truncated to precision
 * @param y - Value to subtract
 */
minus(y: Numeric): Decimal;
sub(y: Numeric): Decimal;  // Alias for minus

/**
 * Multiplication - returns this * y, truncated to precision
 * @param y - Value to multiply by
 */
times(y: Numeric): Decimal;
mul(y: Numeric): Decimal;  // Alias for times

/**
 * Division - returns this / y, truncated to precision
 * @param y - Value to divide by
 */
dividedBy(y: Numeric): Decimal;
div(y: Numeric): Decimal;  // Alias for dividedBy

/**
 * Integer division - returns integer part of this / y
 * @param y - Value to divide by
 */
dividedToIntegerBy(y: Numeric): Decimal;
idiv(y: Numeric): Decimal;  // Alias for dividedToIntegerBy

/**
 * Modulo - returns this % y, truncated to precision
 * @param y - Modulo value
 */
modulo(y: Numeric): Decimal;
mod(y: Numeric): Decimal;  // Alias for modulo

/**
 * Returns absolute value of this Decimal
 */
absoluteValue(): Decimal;
abs(): Decimal;  // Alias for absoluteValue

/**
 * Returns negated value (-this)
 */
negated(): Decimal;
neg(): Decimal;  // Alias for negated

Advanced Mathematical Functions

Higher-level mathematical operations with configurable precision.

/**
 * Exponentiation - returns this^y, uses exp(y*ln(x)) for non-integers
 * @param y - Exponent value
 */
toPower(y: Numeric): Decimal;
pow(y: Numeric): Decimal;  // Alias for toPower

/**
 * Returns square root, truncated to precision digits
 */
squareRoot(): Decimal;
sqrt(): Decimal;  // Alias for squareRoot

/**
 * Returns e^this (natural exponential), truncated to precision
 */
naturalExponential(): Decimal;
exp(): Decimal;  // Alias for naturalExponential

/**
 * Returns natural logarithm of this, truncated to precision
 */
naturalLogarithm(): Decimal;
ln(): Decimal;  // Alias for naturalLogarithm

/**
 * Returns logarithm to specified base (default base 10)
 * @param base - Optional base, defaults to 10
 */
logarithm(base?: Numeric): Decimal;
log(base?: Numeric): Decimal;  // Alias for logarithm

Comparison Methods

Boolean comparison operations for Decimal values.

/**
 * Returns 1 if this > y, -1 if this < y, 0 if equal
 * @param y - Value to compare against
 */
comparedTo(y: Numeric): 1 | 0 | -1;
cmp(y: Numeric): 1 | 0 | -1;  // Alias for comparedTo

/**
 * Returns true if this equals y
 * @param y - Value to compare against
 */
equals(y: Numeric): boolean;
eq(y: Numeric): boolean;  // Alias for equals

/**
 * Returns true if this > y
 * @param y - Value to compare against
 */
greaterThan(y: Numeric): boolean;
gt(y: Numeric): boolean;  // Alias for greaterThan

/**
 * Returns true if this >= y
 * @param y - Value to compare against
 */
greaterThanOrEqualTo(y: Numeric): boolean;
gte(y: Numeric): boolean;  // Alias for greaterThanOrEqualTo

/**
 * Returns true if this < y
 * @param y - Value to compare against
 */
lessThan(y: Numeric): boolean;
lt(y: Numeric): boolean;  // Alias for lessThan

/**
 * Returns true if this <= y
 * @param y - Value to compare against
 */
lessThanOrEqualTo(y: Numeric): boolean;
lte(y: Numeric): boolean;  // Alias for lessThanOrEqualTo

Property and State Methods

Methods for inspecting Decimal properties and state.

/**
 * Returns true if this is an integer
 */
isInteger(): boolean;
isint(): boolean;  // Alias for isInteger

/**
 * Returns true if this is negative
 */
isNegative(): boolean;
isneg(): boolean;  // Alias for isNegative

/**
 * Returns true if this is positive
 */
isPositive(): boolean;
ispos(): boolean;  // Alias for isPositive

/**
 * Returns true if this equals zero
 */
isZero(): boolean;

/**
 * Returns number of decimal places
 */
decimalPlaces(): number;
dp(): number;  // Alias for decimalPlaces

/**
 * Returns number of significant digits
 * @param zeros - Whether to count trailing zeros
 */
precision(zeros: boolean | number): number;
sd(zeros: boolean | number): number;  // Alias for precision

/**
 * Returns base 10 exponent value
 */
exponent(): number;

Formatting and Conversion Methods

Methods for converting Decimal values to different formats and representations.

/**
 * Returns rounded to maximum dp decimal places
 * @param dp - Decimal places
 * @param rm - Rounding mode
 */
toDecimalPlaces(dp?: number, rm?: number): Decimal;
todp(dp?: number, rm?: number): Decimal;  // Alias for toDecimalPlaces

/**
 * Returns rounded to maximum sd significant digits
 * @param sd - Significant digits
 * @param rm - Rounding mode
 */
toSignificantDigits(sd?: number, rm?: number): Decimal;
tosd(sd?: number, rm?: number): Decimal;  // Alias for toSignificantDigits

/**
 * Returns rounded to whole number using rounding mode
 */
toInteger(): Decimal;
toint(): Decimal;  // Alias for toInteger

/**
 * Returns fixed-point notation string
 * @param dp - Decimal places
 * @param rm - Rounding mode
 */
toFixed(dp?: number, rm?: number): string;

/**
 * Returns exponential notation string
 * @param dp - Decimal places
 * @param rm - Rounding mode
 */
toExponential(dp?: number, rm?: number): string;

/**
 * Returns string with sd significant digits, may use exponential notation
 * @param sd - Significant digits
 * @param rm - Rounding mode
 */
toPrecision(sd?: number, rm?: number): string;

/**
 * Returns string representation, uses exponential if needed
 */
toString(): string;
valueOf(): string;  // Alias for toString
val(): string;      // Alias for toString  
toJSON(): string;   // Alias for toString

/**
 * Returns JavaScript number primitive (may lose precision)
 */
toNumber(): number;

Static Methods and Configuration

Class-level methods for configuration and cloning.

/**
 * Creates new Decimal constructor with same/modified configuration
 * @param config - Optional configuration object
 */
static clone(config?: Config): typeof Decimal;

/**
 * Configure global settings for this Decimal constructor
 * @param config - Configuration object
 */
static config(config: Config): Decimal;
static set(config: Config): Decimal;  // Alias for config

Static Properties and Constants

Global configuration properties and rounding mode constants.

// Configuration properties
static precision: number;  // Maximum significant digits (default: 20)
static rounding: number;   // Default rounding mode (default: 4)
static toExpNeg: number;   // Exponent threshold for exponential notation (default: -7)
static toExpPos: number;   // Exponent threshold for exponential notation (default: 21)
static LN10: Decimal;      // Natural logarithm of 10

// Rounding mode constants
static readonly ROUND_UP: number;         // Away from zero
static readonly ROUND_DOWN: number;       // Towards zero
static readonly ROUND_CEIL: number;       // Towards +Infinity
static readonly ROUND_FLOOR: number;      // Towards -Infinity
static readonly ROUND_HALF_UP: number;    // Towards nearest, if equidistant then up
static readonly ROUND_HALF_DOWN: number;  // Towards nearest, if equidistant then down
static readonly ROUND_HALF_EVEN: number;  // Towards nearest, if equidistant then even
static readonly ROUND_HALF_CEIL: number;  // Towards nearest, if equidistant then +Infinity
static readonly ROUND_HALF_FLOOR: number; // Towards nearest, if equidistant then -Infinity

Types

/**
 * Configuration interface for Decimal settings
 */
interface Config {
  precision?: number;
  rounding?: number;
  toExpNeg?: number;
  toExpPos?: number;
  LN10?: Numeric;
}

/**
 * Union type for values accepted by Decimal operations
 */
type Numeric = string | number | Decimal;

Key Differences from decimal.js

  • Size: 12.7 KB vs 32.1 KB minified
  • No NaN/Infinity: Doesn't handle NaN, Infinity, or -0 values
  • No Other Bases: Only works with base 10 numbers
  • Arithmetic Truncation: Arithmetic operations truncate rather than round by default
  • Limited Precision: Math functions (exp, ln, log, pow) have ~100 digit precision limit by default
  • Internal Exponent: Uses base 10000000 exponents internally (use exponent() method for base 10)

Error Handling

The library throws descriptive errors for invalid operations:

  • [DecimalError] Invalid argument: for invalid constructor arguments
  • [DecimalError] Exponent out of range: for exponents outside safe range
  • [DecimalError] NaN for invalid mathematical operations
  • [DecimalError] Division by zero for division by zero
  • [DecimalError] Infinity for operations resulting in infinity

Configuration Examples

// Configure precision and rounding globally
Decimal.config({
  precision: 40,
  rounding: Decimal.ROUND_HALF_UP,
  toExpNeg: -10,
  toExpPos: 30
});

// Create a new constructor with different settings
const MyDecimal = Decimal.clone({
  precision: 100,
  rounding: Decimal.ROUND_DOWN
});

// High precision mathematical operations
Decimal.set({
  // 415 digits for natural log calculations
  LN10: '2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286248633409525465082806756666287369098781689482907208325554680843799894826233198528393505308965377732628846163366222287698219886746543667474404243274365155048934314939391479619404400222105101714174800368808401264708068556774321622835522011480466371565912137345074785694768346361679210180644507064800027'
});

Usage Patterns

Financial Calculations

// Currency calculations with exact precision
const price = new Decimal("19.95");
const taxRate = new Decimal("0.08");
const tax = price.times(taxRate);
const total = price.plus(tax);

console.log(`Total: $${total.toFixed(2)}`); // "Total: $21.55"

Scientific Computing

// High-precision scientific calculations
const radius = new Decimal("6371000"); // Earth radius in meters
const pi = new Decimal("3.141592653589793238462643383279502884197");
const circumference = pi.times(2).times(radius);

console.log(circumference.toString()); // Exact circumference

Chained Operations

// Complex calculations with method chaining
const result = new Decimal("100")
  .dividedBy("3")
  .times("2")
  .plus("10")
  .toDecimalPlaces(2);

console.log(result.toString()); // "76.67"

Install with Tessl CLI

npx tessl i tessl/npm-decimal-js-light
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/decimal.js-light@2.5.x
Publish Source
CLI
Badge
tessl/npm-decimal-js-light badge