or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

arithmetic.mdcomparison-utility.mdconfiguration.mdformatting.mdindex.mdmath-functions.mdtrig-functions.md
tile.json

configuration.mddocs/

Configuration and Constructor Methods

Configuration management, constructor cloning, and precision control for advanced usage scenarios. These methods enable fine-tuned control over Decimal behavior, precision settings, and the creation of independent Decimal constructors.

Capabilities

Configuration Management

Configure global Decimal behavior and precision settings.

/**
 * Configuration object for Decimal constructor settings
 */
interface Decimal.Config {
  /** Number of significant digits (1 to 1e9, default: 20) */
  precision?: number;
  /** Rounding mode (0-8, default: 4 ROUND_HALF_UP) */
  rounding?: Decimal.Rounding;
  /** Exponential notation threshold for small numbers (default: -7) */
  toExpNeg?: number;
  /** Exponential notation threshold for large numbers (default: 21) */
  toExpPos?: number;
  /** Minimum exponent value (default: -9e15) */
  minE?: number;
  /** Maximum exponent value (default: 9e15) */
  maxE?: number;
  /** Use cryptographically secure random number generation (default: false) */
  crypto?: boolean;
  /** Modulo mode (0-9, default: 1) */
  modulo?: Decimal.Modulo;
  /** Reset to default configuration if true */
  defaults?: boolean;
}

/**
 * Configure the default Decimal constructor
 * @param options - Configuration options
 * @returns The Decimal constructor
 */
static config(options: Decimal.Config): Decimal.Constructor;
static set(options: Decimal.Config): Decimal.Constructor; // Alias for config

Usage Examples:

import Decimal from "decimal.js";

// Set global precision
Decimal.config({ precision: 50 });
const highPrecision = new Decimal('1').div('3');
// Result has 50 significant digits

// Configure rounding mode
Decimal.set({ 
  precision: 10,
  rounding: Decimal.ROUND_UP 
});

const rounded = new Decimal('1.23456789012345').plus('0');
// All operations now round up

// Configure exponential notation thresholds
Decimal.config({
  toExpNeg: -3,  // Use exponential for numbers < 0.001
  toExpPos: 6    // Use exponential for numbers >= 1000000
});

new Decimal('0.0005').toString();    // '5e-4'
new Decimal('2000000').toString();   // '2e+6'

// Configure crypto random
Decimal.config({ crypto: true });
const secureRandom = Decimal.random(); // Uses crypto.getRandomValues if available

// Reset to defaults
Decimal.config({ defaults: true });

Constructor Cloning

Create independent Decimal constructors with their own configuration.

/**
 * Create a new Decimal constructor with independent configuration
 * @param options - Configuration options for the new constructor
 * @returns New Decimal constructor with independent settings
 */
static clone(options?: Decimal.Config): Decimal.Constructor;

Usage Examples:

// Create specialized Decimal constructors
const HighPrecisionDecimal = Decimal.clone({ precision: 100 });
const CurrencyDecimal = Decimal.clone({ 
  precision: 4,
  rounding: Decimal.ROUND_HALF_EVEN 
});
const ScientificDecimal = Decimal.clone({
  precision: 15,
  toExpNeg: -5,
  toExpPos: 5
});

// Each constructor operates independently
const standard = new Decimal('1').div('3');        // Uses default precision (20)
const highPrec = new HighPrecisionDecimal('1').div('3'); // Uses 100 digits
const currency = new CurrencyDecimal('10.555');     // Rounds to 4 significant digits

// Original Decimal is unchanged
Decimal.precision;                    // Still 20
HighPrecisionDecimal.precision;       // 100
CurrencyDecimal.precision;            // 4

// Configure cloned constructors independently
HighPrecisionDecimal.config({ rounding: Decimal.ROUND_DOWN });
// Does not affect original Decimal or other clones

Configuration Properties

Access current configuration settings (read-only).

/**
 * Current configuration properties (read-only)
 */
static readonly precision: number;
static readonly rounding: Decimal.Rounding;
static readonly toExpNeg: number;
static readonly toExpPos: number;
static readonly minE: number;
static readonly maxE: number;
static readonly crypto: boolean;
static readonly modulo: Decimal.Modulo;

Usage Examples:

// Check current configuration
console.log('Current precision:', Decimal.precision);     // 20
console.log('Current rounding:', Decimal.rounding);       // 4
console.log('Crypto enabled:', Decimal.crypto);           // false
console.log('Min exponent:', Decimal.minE);               // -9000000000000000
console.log('Max exponent:', Decimal.maxE);               // 9000000000000000

// Use configuration in logic
function createOptimalDecimal(value) {
  if (Decimal.precision < 50) {
    // Increase precision for this calculation
    const HighPrecDecimal = Decimal.clone({ precision: 50 });
    return new HighPrecDecimal(value);
  }
  return new Decimal(value);
}

Random Number Generation

Generate cryptographically secure or pseudo-random Decimal numbers.

/**
 * Return a new Decimal with a random value >= 0 and < 1
 * @param significantDigits - Number of significant digits (optional, uses current precision)
 * @returns New Decimal instance with random value
 */
static random(significantDigits?: number): Decimal;

Usage Examples:

// Basic random generation
const random1 = Decimal.random();                    // Uses current precision
const random2 = Decimal.random(10);                  // Exactly 10 significant digits

// Cryptographically secure random (if crypto: true)
Decimal.config({ crypto: true });
const secureRandom = Decimal.random();               // Uses crypto.getRandomValues

// Generate random numbers in specific ranges
function randomInRange(min, max) {
  const range = new Decimal(max).minus(min);
  return Decimal.random().times(range).plus(min);
}

const randomBetween1And10 = randomInRange('1', '10');
const randomPercent = Decimal.random().times('100');  // 0-100

// Generate random integers
function randomInteger(min, max) {
  const range = new Decimal(max).minus(min).plus('1');
  return Decimal.random().times(range).plus(min).floor();
}

const randomDice = randomInteger(1, 6);              // 1-6

Browser Compatibility Methods

Browser-specific methods for global variable management.

/**
 * Restore the global Decimal variable to its previous value (browser only)
 * @returns The Decimal constructor
 */
static noConflict(): Decimal.Constructor;

Usage Examples:

// Browser environment only
// If another library also uses 'Decimal' globally
const MyDecimal = Decimal.noConflict();
// Global 'Decimal' is restored to previous value
// Use MyDecimal for this library's Decimal functionality

const value = new MyDecimal('123.456');

Type Checking and Validation

Methods for type checking and validation.

/**
 * Return true if object is a Decimal instance (from any Decimal constructor)
 * @param obj - Object to test
 * @returns Boolean indicating if object is a Decimal instance
 */
static isDecimal(obj: any): obj is Decimal;

Usage Examples:

const decimal = new Decimal('123');
const clonedDecimal = new (Decimal.clone())('456');
const number = 123;
const string = '123';

Decimal.isDecimal(decimal);        // true
Decimal.isDecimal(clonedDecimal);  // true (works across cloned constructors)
Decimal.isDecimal(number);         // false
Decimal.isDecimal(string);         // false

// Use in type guards
function processValue(value: unknown) {
  if (Decimal.isDecimal(value)) {
    // TypeScript knows value is Decimal here
    return value.plus('10');
  }
  return new Decimal(value).plus('10');
}

Advanced Configuration Scenarios

Complex configuration setups for specialized use cases.

Usage Examples:

// Financial calculations constructor
const FinancialDecimal = Decimal.clone({
  precision: 28,                    // High precision for financial accuracy
  rounding: Decimal.ROUND_HALF_EVEN, // Banker's rounding
  toExpNeg: -15,                    // Avoid exponential notation for small amounts
  toExpPos: 15                      // Avoid exponential notation for large amounts
});

// Scientific calculations constructor  
const ScientificDecimal = Decimal.clone({
  precision: 50,                    // Very high precision
  rounding: Decimal.ROUND_HALF_UP,  // Standard scientific rounding
  crypto: true                      // Secure random for simulations
});

// Performance-optimized constructor
const FastDecimal = Decimal.clone({
  precision: 10,                    // Lower precision for speed
  rounding: Decimal.ROUND_DOWN      // Fastest rounding mode
});

// Configuration for specific domains
const CryptoDecimal = Decimal.clone({
  precision: 18,                    // Match cryptocurrency precision (like Ethereum Wei)
  rounding: Decimal.ROUND_DOWN,     // Prevent rounding up in transfers
  crypto: true                      // Secure random for key generation
});

// Temperature conversion with appropriate precision
const TemperatureDecimal = Decimal.clone({
  precision: 6,                     // Sufficient for temperature measurements
  rounding: Decimal.ROUND_HALF_EVEN
});

// Usage in calculations
const btcAmount = new CryptoDecimal('0.123456789012345678');
const temperature = new TemperatureDecimal('98.6');
const scientificResult = new ScientificDecimal('1').div('3');

Error Handling and Validation

Configuration methods include validation and error handling.

// Invalid configurations throw errors
try {
  Decimal.config({ precision: 0 });          // Error: precision out of range
} catch (error) {
  console.error('Invalid precision setting');
}

try {
  Decimal.config({ rounding: 10 });          // Error: invalid rounding mode
} catch (error) {
  console.error('Invalid rounding mode');
}

try {
  Decimal.config({ maxE: 1e20 });            // Error: exponent out of range
} catch (error) {
  console.error('Exponent limit exceeded');
}

// Safe configuration with validation
function safeConfig(options) {
  try {
    Decimal.config(options);
    return true;
  } catch (error) {
    console.warn('Configuration failed:', error.message);
    return false;
  }
}

const success = safeConfig({ precision: 30, rounding: 2 });