### Install Decimal.js for Node.js Source: https://github.com/mikemcl/decimal.js/blob/master/README.md Install the decimal.js package using npm for use in Node.js projects. ```bash npm install decimal.js ``` -------------------------------- ### Decimal.Modulo Usage Examples Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/types.md Illustrates setting the modulo mode for operations. Examples show configuring DOWN, FLOOR, and the EUCLID mode for always positive remainders. ```javascript const Decimal = require('decimal.js'); Decimal.set({ modulo: 1 }); // DOWN (same as JavaScript %) Decimal.set({ modulo: 3 }); // FLOOR (same as Python %) Decimal.set({ modulo: Decimal.EUCLID }); // Always positive remainder ``` -------------------------------- ### Financial Calculation Example Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/index.md Demonstrates how to perform financial calculations with specific precision and rounding settings. ```javascript const Decimal = require('decimal.js'); Decimal.set({ precision: 28, rounding: Decimal.ROUND_HALF_UP }); function calculateTax(amount, rate) { const decimal_amount = new Decimal(amount); const decimal_rate = new Decimal(rate); return decimal_amount.times(decimal_rate).toDP(2); } calculateTax('99.99', '0.07'); // Tax calculation ``` -------------------------------- ### Multiple Precision Requirements Example Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/index.md Shows how to use different Decimal instances with varying precision requirements. ```javascript const Decimal = require('decimal.js'); const Precise = Decimal.clone({ precision: 100 }); // High precision const Display = Decimal.clone({ precision: 2 }); // Rounded display const value = new Precise('19.99').div(3); const displayed = new Display(value); ``` -------------------------------- ### Decimal.Value Usage Examples Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/types.md Demonstrates creating Decimal instances and performing operations using various Decimal.Value types. Ensure the 'decimal.js' library is required. ```javascript const Decimal = require('decimal.js'); const x = new Decimal('123.45'); // Decimal.Value as string const y = new Decimal(123.45); // Decimal.Value as number const z = new Decimal(123n); // Decimal.Value as bigint const w = new Decimal(x); // Decimal.Value as Decimal Decimal.add('10', '20'); // Arguments are Decimal.Value x.plus(5); // Method argument is Decimal.Value ``` -------------------------------- ### Error Handling Example Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/index.md Demonstrates how Decimal.js handles invalid arguments and mathematical edge cases. ```javascript const Decimal = require('decimal.js'); // Throws error try { new Decimal('invalid'); } catch (e) { console.error(e.message); // [DecimalError] Invalid argument: invalid } // Returns special values (no error) const nan = new Decimal(NaN); const inf = new Decimal(Infinity).exp(); const negZero = new Decimal('-0'); ``` -------------------------------- ### Decimal.Rounding Usage Examples Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/types.md Shows how to configure rounding modes using either numeric constants or named constants from the Decimal object. Demonstrates applying rounding in method calls. ```javascript const Decimal = require('decimal.js'); // Using numeric constant Decimal.set({ rounding: 4 }); // Using named constant Decimal.set({ rounding: Decimal.ROUND_HALF_UP }); // In method calls new Decimal('2.5').toDP(0, 4); // '3' (ROUND_HALF_UP) ``` -------------------------------- ### Example: Accessing Internal Decimal Properties Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/types.md Demonstrates how to access and log the internal 'd', 'e', and 's' properties of a Decimal number. ```javascript const Decimal = require('decimal.js'); const x = new Decimal('-12345.67'); console.log(x.d); // [ 12345, 6700000 ] console.log(x.e); // 4 console.log(x.s); // -1 // Represents: -1.234567 × 10^4 = -12345.67 ``` -------------------------------- ### Decimal.Instance Usage Examples Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/types.md Demonstrates using Decimal.Instance as a type annotation for function parameters and return types, ensuring type safety for Decimal objects. ```javascript import { Decimal } from 'decimal.js'; function calculate(x: Decimal.Instance, y: Decimal.Instance): Decimal.Instance { return x.plus(y); } // OR equivalently: function calculate(x: Decimal, y: Decimal): Decimal { return x.plus(y); } ``` -------------------------------- ### Chaining Decimal.js Methods in JavaScript Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/getting-started.md Demonstrates how to chain multiple Decimal.js methods together for concise and efficient calculations. This example shows a sequence of arithmetic operations. ```javascript const Decimal = require('decimal.js'); const result = new Decimal('2') .pow(3) // 8 .plus(1) // 9 .sqrt() // 3 .times(2) // 6 .minus(1); // 5 console.log(result.toString()); // '5' // Chaining with configuration Decimal.set({ precision: 20 }) .set({ rounding: 4 }) .set({ modulo: 1 }); ``` -------------------------------- ### Decimal.Constructor Usage Examples Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/types.md Shows how Decimal.Constructor is used to type the results of static methods like Decimal.clone() and Decimal.set(). ```javascript const Decimal = require('decimal.js'); // Result of Decimal.clone() const CustomDecimal = Decimal.clone({ precision: 50 }); // CustomDecimal is of type Decimal.Constructor // Result of Decimal.set() const result = Decimal.set({ precision: 25 }); // result is of type Decimal.Constructor ``` -------------------------------- ### Decimal Constructor Examples Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Demonstrates various ways to instantiate a Decimal object using numbers, strings, BigInts, and other Decimals. Supports different number formats including scientific notation and non-decimal bases. ```javascript x = new Decimal(9) // '9' y = new Decimal(x) // '9' ``` ```javascript new Decimal('5032485723458348569331745.33434346346912144534543') ``` ```javascript new Decimal('4.321e+4') // '43210' ``` ```javascript new Decimal('-735.0918e-430') // '-7.350918e-428' ``` ```javascript new Decimal('5.6700000') // '5.67' ``` ```javascript new Decimal(Infinity) // 'Infinity' ``` ```javascript new Decimal(NaN) // 'NaN' ``` ```javascript new Decimal('.5') // '0.5' ``` ```javascript new Decimal('-0b10110100.1') // '-180.5' ``` ```javascript new Decimal('0xff.8') // '255.5' ``` ```javascript new Decimal(0.046875) // '0.046875' ``` ```javascript new Decimal('0.046875000000') // '0.046875' ``` ```javascript new Decimal('0.04_6875_000_000') // '0.046875' ``` ```javascript new Decimal(4.6875e-2) // '0.046875' ``` ```javascript new Decimal('468.75e-4') // '0.046875' ``` ```javascript new Decimal('0b0.000011') // '0.046875' ``` ```javascript new Decimal('0o0.03') // '0.046875' ``` ```javascript new Decimal('0x0.0c') // '0.046875' ``` ```javascript new Decimal('0b1.1p-5') // '0.046875' ``` ```javascript new Decimal('0o1.4p-5') // '0.046875' ``` ```javascript new Decimal(123456000n) // '123456000' ``` ```javascript new Decimal(BigInt('-1')) // '-1' ``` -------------------------------- ### Financial Calculations with Decimal.js Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/getting-started.md Example of calculating a bill total with tax using Decimal.js, ensuring accurate rounding to cents. ```javascript const Decimal = require('decimal.js'); // Calculate bill total with tax function calculateTotal(subtotal, taxRate) { const sub = new Decimal(subtotal); const rate = new Decimal(taxRate); const tax = sub.times(rate).toDP(2); // Round to cents return sub.plus(tax); } const subtotal = '99.99'; const rate = '0.08'; // 8% const total = calculateTotal(subtotal, rate); console.log(total.toString()); // '107.99' ``` -------------------------------- ### Decimal Immutability Example Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/decimal-constructor.md Illustrates the immutability of Decimal instances. Methods like minus return new Decimal instances, leaving the original instances unchanged. ```javascript const Decimal = require('decimal.js'); const x = new Decimal(0.3); const y = x.minus(0.1); x.toString(); // '0.3' y.toString(); // '0.2' ``` -------------------------------- ### Setting Decimal minimum exponent (minE) using set() Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Configure the negative exponent limit below which underflow to zero occurs using `Decimal.set()`. This example sets `minE` to -500. ```javascript Decimal.set({ minE: -500 }) Decimal.minE // -500 new Decimal('1e-500') // '1e-500' new Decimal('9.9e-501') // '0' ``` -------------------------------- ### Scientific Calculation Example Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/index.md Illustrates scientific calculations using high precision and specific rounding. ```javascript const Decimal = require('decimal.js'); Decimal.set({ precision: 50, rounding: Decimal.ROUND_HALF_EVEN }); const pi = Decimal.acos(-1); const e = new Decimal(1).exp(); const circumference = pi.times(diameter); ``` -------------------------------- ### Setting Decimal maximum exponent (maxE) using set() Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Configure the positive exponent limit above which overflow to Infinity occurs using `Decimal.set()`. This example sets `maxE` to 500. ```javascript Decimal.set({ maxE: 500 }) Decimal.maxE // 500 new Decimal('9.999e500') // '9.999e+500' new Decimal('1e501') // 'Infinity' ``` -------------------------------- ### Minify decimal.js with uglify-js Source: https://github.com/mikemcl/decimal.js/blob/master/README.md Minifies the decimal.js file using uglify-js, generating a source map. Ensure uglify-js is installed globally. ```bash npm install uglify-js -g uglifyjs decimal.js --source-map url=decimal.min.js.map -c -m -o decimal.min.js ``` -------------------------------- ### Decimal Static Arithmetic Methods Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/quick-reference.md Provides examples of static methods for arithmetic operations like add, sub, mul, div, and sum, which can operate on multiple arguments. ```javascript Decimal.add(x, y) Decimal.sub(x, y) Decimal.mul(x, y) Decimal.div(x, y) Decimal.sum(a, b, c) ``` -------------------------------- ### Decimal Trigonometric Functions Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/quick-reference.md Provides examples for trigonometric functions like sine, cosine, tangent, arcsine, arccosine, and arctangent. Input for inverse trigonometric functions is restricted. ```javascript x.sin() x.cos() x.tan() x.asin() x.acos() x.atan() ``` -------------------------------- ### Decimal Arithmetic Operations Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/quick-reference.md Provides examples of common arithmetic operations such as addition, subtraction, multiplication, division, modulo, power, square root, and cube root using Decimal.js methods. ```javascript x.plus(y) x.minus(y) x.times(2) x.dividedBy(y) x.divToInt(y) x.mod(y) x.pow(2) x.sqrt() x.cbrt() ``` -------------------------------- ### Setting Decimal rounding mode using set() Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Configure the default rounding mode for Decimal operations using `Decimal.set()`. This example sets the rounding mode to ROUND_UP. ```javascript Decimal.set({ rounding: Decimal.ROUND_UP }) Decimal.set({ rounding: 0 }) // equivalent Decimal.rounding // 0 ``` -------------------------------- ### Decimal Constructor Configuration Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/decimal-constructor.md Shows how to create Decimal instances with default configuration, change the global configuration using Decimal.set, and create new constructors with specific configurations using Decimal.clone. ```javascript const Decimal = require('decimal.js'); // Create instance with default configuration const x = new Decimal(5); x.div(3); // '1.66666666666666667' (20 digit precision) // Change global configuration Decimal.set({ precision: 5, rounding: 4 }); const y = new Decimal(5); y.div(3); // '1.6667' // Create a new constructor with different configuration const Dec = Decimal.clone({ precision: 9 }); const z = new Dec(5); z.div(3); // '1.66666667' ``` -------------------------------- ### Get the Value of Pi Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Retrieve the value of pi using the acos method. ```javascript pi = Decimal.acos(-1) ``` -------------------------------- ### Get Negated Value (Alias) Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/instance-methods.md Returns the negation of a Decimal number. This is an alias for negated. ```javascript const Decimal = require('decimal.js'); new Decimal('-5').neg().toString(); // '5' ``` -------------------------------- ### Get Number of Decimal Places Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Returns the count of digits after the decimal point for this Decimal. ```javascript x = new Decimal(1.234) x.decimalPlaces() // '3' y = new Decimal(987.654321) y.dp() // '6' ``` -------------------------------- ### Configuring Precision Levels with Decimal.js Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/getting-started.md Demonstrates how to set the global precision for Decimal.js calculations and how to create separate constructors with different precision settings. ```javascript const Decimal = require('decimal.js'); // High precision for calculations Decimal.set({ precision: 50 }); const calc = new Decimal('1').div('3'); console.log(calc.toString()); // 0.33333333333333333333333333333333333333333333333333 // Create low-precision constructor for quick operations const Quick = Decimal.clone({ precision: 10 }); const quick = new Quick('1').div('3'); console.log(quick.toString()); // 0.3333333333 // Display with just 2 significant figures const Display = Decimal.clone({ precision: 2 }); const display = new Display(calc); console.log(display.toString()); // 0.33 ``` -------------------------------- ### Instance Methods Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Methods available on Decimal instances. ```APIDOC ### Instance Methods - **absoluteValue()**: abs - **ceil()**: ceil - **comparedTo(other)**: cmp - **clampedTo(lower, upper)**: clamp - **cosine()**: cos - **cubeRoot()**: cbrt - **decimalPlaces()**: dp - **dividedBy(divisor)**: div - **dividedToIntegerBy(divisor)**: divToInt - **equals(other)**: eq - **floor()**: floor - **greaterThan(other)**: gt - **greaterThanOrEqualTo(other)**: gte - **hyperbolicCosine()**: cosh - **hyperbolicSine()**: sinh - **hyperbolicTangent()**: tanh - **inverseCosine()**: acos - **inverseHyperbolicCosine()**: acosh - **inverseHyperbolicSine()**: asinh - **inverseHyperbolicTangent()**: atanh - **inverseSine()**: asin - **inverseTangent()**: atan - **isFinite()**: isFinite - **isInteger()**: isInt - **isNaN()**: isNaN - **isNegative()**: isNeg - **isPositive()**: isPos - **isZero()**: isZero - **lessThan(other)**: lt - **lessThanOrEqualTo(other)**: lte - **logarithm(base)**: log - **minus(subtrahend)**: sub - **modulo(divisor)**: mod - **naturalExponential()**: exp - **naturalLogarithm()**: ln - **negated()**: neg - **plus(addend)**: add - **precision()**: sd - **round()**: round - **sine()**: sin - **squareRoot()**: sqrt - **tangent()**: tan - **hyperbolicTangent()**: tanh - **times(multiplier)**: mul - **toBinary()**: toBinary - **toDecimalPlaces(decimalPlaces)**: toDP - **toExponential(fractionDigits)**: toExponential - **toFixed(decimalPlaces)**: toFixed - **toFraction()**: toFraction ``` -------------------------------- ### Get Number of Significant Digits (Alias) Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/instance-methods.md Returns the number of significant digits. This is an alias for precision. ```javascript const Decimal = require('decimal.js'); new Decimal('12345.67').sd(); // 7 ``` -------------------------------- ### Get Absolute Value (Alias) Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/instance-methods.md Returns the absolute value of a Decimal number. This is an alias for absoluteValue. ```javascript const Decimal = require('decimal.js'); new Decimal('-5').abs().toString(); // '5' ``` -------------------------------- ### Decimal Creation from Different Number Formats Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/decimal-constructor.md Demonstrates creating Decimal instances from binary, hexadecimal, octal, exponential notation, and numbers with underscore separators. ```javascript const Decimal = require('decimal.js'); // Binary const bin = new Decimal('0xff.f'); // 255.9375 const bin2 = new Decimal('0b10101100'); // 172 // Hexadecimal const hex = new Decimal('0x1a.2b'); // 26.169921875 // Octal const oct = new Decimal('0o77'); // 63 // Exponential notation const exp = new Decimal('1.5e+10'); // 15000000000 // With underscores (ES2021 feature) const underscore = new Decimal('1_000_000.50'); ``` -------------------------------- ### Default Configuration for Decimal.js Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/getting-started.md Shows how to check the current global configuration settings for Decimal.js, such as precision and rounding mode. It also demonstrates how to change these settings globally. ```javascript const Decimal = require('decimal.js'); // Check current settings console.log(Decimal.precision); // 20 console.log(Decimal.rounding); // 4 (ROUND_HALF_UP) // Change globally Decimal.set({ precision: 50, rounding: Decimal.ROUND_HALF_EVEN }); ``` -------------------------------- ### Get String Value Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/instance-methods.md Returns the string representation of a Decimal number. This method is an alias for toJSON. ```javascript const Decimal = require('decimal.js'); new Decimal('123.45').valueOf(); // '123.45' ``` -------------------------------- ### maxE Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Gets or sets the maximum positive exponent before overflow to Infinity occurs. Default is 9e15. ```APIDOC ## maxE ### Description Gets or sets the positive exponent limit. If a calculation's result has an exponent higher than this value, it will be treated as Infinity. The default value is 9e15. ### Property `Decimal.maxE` ### Type number ### Example ```javascript // Get current maximum exponent console.log(Decimal.maxE); // Set maximum exponent to 500 Decimal.set({ maxE: 500 }); console.log(Decimal.maxE); // Output: 500 ``` ``` -------------------------------- ### minE Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Gets or sets the minimum negative exponent before underflow to zero occurs. Default is -9e15. ```APIDOC ## minE ### Description Gets or sets the negative exponent limit. If a calculation's result has an exponent lower than this value, it will be treated as zero. The default value is -9e15. ### Property `Decimal.minE` ### Type number ### Example ```javascript // Get current minimum exponent console.log(Decimal.minE); // Set minimum exponent to -500 Decimal.set({ minE: -500 }); console.log(Decimal.minE); // Output: -500 ``` ``` -------------------------------- ### rounding Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Gets or sets the default rounding mode for Decimal operations. Default is ROUND_HALF_UP (4). ```APIDOC ## rounding ### Description Gets or sets the default rounding mode used for operations. The default value is 4 (ROUND_HALF_UP). Refer to the [modes](#modes) section for available rounding modes. ### Property `Decimal.rounding` ### Type number ### Example ```javascript // Get current rounding mode console.log(Decimal.rounding); // Set rounding mode to ROUND_UP (0) Decimal.set({ rounding: Decimal.ROUND_UP }); console.log(Decimal.rounding); // Output: 0 ``` ``` -------------------------------- ### Decimal Properties and Tests Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/quick-reference.md Demonstrates how to retrieve properties like precision and decimal places, and perform tests for finiteness, NaN, integer, positive, and negative values. Also includes absolute value, negation, and clamping. ```javascript x.precision() x.dp() x.isFinite() x.isNaN() x.isInt() x.isZero() x.isPos() x.isNeg() x.abs() x.neg() x.clamp(0, 10) ``` -------------------------------- ### precision Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Gets or sets the maximum number of significant digits for Decimal operations. Default is 20. ```APIDOC ## precision ### Description Gets or sets the maximum number of significant digits that operations will be rounded to. The default value is 20. ### Property `Decimal.precision` ### Type number ### Example ```javascript // Get current precision console.log(Decimal.precision); // Set precision to 5 Decimal.set({ precision: 5 }); console.log(Decimal.precision); // Output: 5 ``` ``` -------------------------------- ### set Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Configures the global settings for a Decimal constructor. ```APIDOC ## set ### Description Configures the 'global' settings for a specific Decimal constructor, affecting operations performed on Decimal instances created by it. Returns the Decimal constructor. ### Method `Decimal.set(object)` ### Parameters - **object**: object - An object containing configuration properties. Supported properties include: `precision`, `rounding`, `toExpNeg`, `toExpPos`, `maxE`, `minE`, `modulo`, `crypto`. If the `'defaults'` property is set to `true`, unspecified properties will be reset to their default values. ### Response - Decimal constructor: The Decimal constructor itself, allowing for chaining. ### Example ```javascript // Set precision to 50 and reset others to defaults Decimal.set({ precision: 50, defaults: true }) // Reset all properties to their default values Decimal.set({ defaults: true }) ``` ### Error Handling Throws an error on an invalid `object` or configuration property value. ``` -------------------------------- ### Get Number of Decimal Places (Alias) Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/instance-methods.md Returns the number of digits after the decimal point. This is an alias for decimalPlaces. ```javascript const Decimal = require('decimal.js'); new Decimal('12.345').dp(); // 3 ``` -------------------------------- ### Get Negated Value Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/instance-methods.md Returns the negation of a Decimal number, flipping its sign. This method is an alias for neg. ```javascript const Decimal = require('decimal.js'); new Decimal('5').negated().toString(); // '-5' ``` -------------------------------- ### Initialize Decimal Instances Source: https://github.com/mikemcl/decimal.js/blob/master/README.md Create Decimal instances from numbers, strings, or other Decimal instances. Use strings for values with many digits to avoid precision loss. ```javascript x = new Decimal(123.4567) y = new Decimal('123456.7e-3') z = new Decimal(x) x.equals(y) && y.equals(z) && x.equals(z) // true ``` -------------------------------- ### Error Handling with Decimal.js Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/getting-started.md Illustrates how to handle configuration errors and invalid input types using try-catch blocks. It also shows how to check for special numeric values like infinity and NaN. ```javascript const Decimal = require('decimal.js'); // Try-catch for configuration errors try { Decimal.set({ precision: 0 }); // Invalid } catch (error) { console.error('Config error:', error.message); Decimal.set({ precision: 20 }); // Use default } // Check for invalid input types try { new Decimal({ value: 5 }); // Objects not supported } catch (error) { console.error('Type error:', error.message); } // Handle mathematical edge cases (no error, special values) const zero = new Decimal(0); const inf = zero.exp(); // Actually not infinity, but a large number const nan = new Decimal(NaN); console.log(inf.isFinite()); // true (unless overflow occurs) console.log(nan.isNaN()); // true ``` -------------------------------- ### Get Absolute Value Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/instance-methods.md Returns the absolute value of a Decimal number, effectively removing the sign. This method is an alias for abs. ```javascript const Decimal = require('decimal.js'); new Decimal('-5').absoluteValue().toString(); // '5' ``` -------------------------------- ### Set Multiple Configuration Options Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/configuration.md Use `Decimal.set()` to configure multiple options at once. This method returns the Decimal constructor for chaining. ```javascript const Decimal = require('decimal.js'); // Set multiple options Decimal.set({ precision: 50, rounding: Decimal.ROUND_HALF_EVEN, toExpNeg: -10, toExpPos: 25 }); ``` -------------------------------- ### Get String Representation for Serialization Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/instance-methods.md Returns the string representation of a Decimal number, suitable for serialization. This method is an alias for valueOf. ```javascript const Decimal = require('decimal.js'); new Decimal('123.45').toJSON(); // '123.45' ``` -------------------------------- ### Run All Tests with Node.js Source: https://github.com/mikemcl/decimal.js/blob/master/README.md Execute all test modules using npm test from the root directory. ```bash npm test ``` -------------------------------- ### Working with Fractions using Decimal.js Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/getting-started.md Explains how to convert between decimal and fraction representations using Decimal.js. It covers converting to exact and approximate fractions, and converting fractions back to decimals. ```javascript const Decimal = require('decimal.js'); // Convert decimal to fraction const decimal = new Decimal('0.3333333333'); const [num, denom] = decimal.toFraction(); console.log(`${num}/${denom}`); // '3333333333/10000000000' (exact) // With max denominator const [n, d] = decimal.toFraction(100); console.log(`${n}/${d}`); // '1/3' (approximate, simpler) // Convert fraction to decimal const fraction = new Decimal('22').div('7'); // π approximation console.log(fraction.toString()); // '3.142857142857142857142857...' ``` -------------------------------- ### Get Absolute Value of a Decimal Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Returns a new Decimal with the absolute value of the original. The precision setting does not affect the result. ```javascript x = new Decimal(-0.8) y = x.absoluteValue() // '0.8' z = y.abs() // '0.8' ``` -------------------------------- ### Per-Calculation Configuration in Decimal.js Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/getting-started.md Illustrates how to temporarily change Decimal.js configuration for a specific calculation and then restore the original settings. This is useful for operations requiring different precision levels. ```javascript const Decimal = require('decimal.js'); // Save current settings const savedPrecision = Decimal.precision; // Change for a specific calculation Decimal.set({ precision: 100 }); const result = new Decimal('1').div('3'); // Restore settings Decimal.set({ precision: savedPrecision }); ``` -------------------------------- ### Get Absolute Value Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/static-methods.md Use `Decimal.abs` to return the absolute (non-negative) value of a Decimal number. This is useful for ensuring a value is positive. ```javascript const Decimal = require('decimal.js'); Decimal.abs('-5').toString(); // '5' ``` -------------------------------- ### Configure Decimal.js Globally or Per Instance Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/index.md Adjust global configuration for precision and rounding using Decimal.set(). Create independent Decimal constructors with specific configurations using Decimal.clone(). ```javascript const Decimal = require('decimal.js'); // Set global configuration Decimal.set({ precision: 50, rounding: 4 }); // Create independent Decimal with different config const HighPrec = Decimal.clone({ precision: 100 }); const LowPrec = Decimal.clone({ precision: 5 }); const x = new Decimal(1).div(3); const y = new HighPrec(1).div(3); x.toString(); // 20 significant digits (default) y.toString(); // 100 significant digits ``` -------------------------------- ### Minify decimal.mjs with terser Source: https://github.com/mikemcl/decimal.js/blob/master/README.md Minifies the ES module version (decimal.mjs) using terser, generating a source map. Ensure terser is installed globally. ```bash npm install terser -g terser decimal.mjs --source-map url=decimal.min.mjs.map -c -m --toplevel -o decimal.min.mjs ``` -------------------------------- ### Run Individual Test Module Source: https://github.com/mikemcl/decimal.js/blob/master/README.md Execute a specific test module, such as 'toFraction', using Node.js. ```bash node test/modules/toFraction ``` -------------------------------- ### Decimal Comparison Operations Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/quick-reference.md Illustrates how to compare Decimal instances using methods like equals, comparedTo, greaterThan, greaterThanOrEqualTo, lessThan, and lessThanOrEqualTo. ```javascript x.eq(y) x.cmp(y) x.gt(y) x.gte(y) x.lt(y) x.lte(y) ``` -------------------------------- ### Import Decimal.js in Node.js (CommonJS) Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/getting-started.md Import the Decimal class in Node.js environments using require. Demonstrates basic addition. ```javascript const Decimal = require('decimal.js'); const x = new Decimal('0.1'); const y = new Decimal('0.2'); console.log(x.plus(y).toString()); // '0.3' ``` -------------------------------- ### Example of Incorrect Rounding with pow Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Demonstrates a scenario where the `pow` method might produce an incorrectly rounded result due to the nature of floating-point calculations and rounding modes. ```javascript Decimal.set({ precision: 20, rounding: 1 }) new Decimal(28).pow('6.166675020000903537297764507632802193308677149') // 839756321.64088511 ``` -------------------------------- ### Load Decimal.js in Node.js (Import Destructuring) Source: https://github.com/mikemcl/decimal.js/blob/master/README.md Import the Decimal class using destructuring syntax from the decimal.js package in Node.js. ```javascript import {Decimal} from 'decimal.js'; ``` -------------------------------- ### Setting Decimal precision using set() Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Configure the maximum number of significant digits for Decimal operations using `Decimal.set()`. This example shows setting precision to 5. ```javascript Decimal.set({ precision: 5 }) Decimal.precision // 5 ``` -------------------------------- ### Number and Math Method Replications Source: https://github.com/mikemcl/decimal.js/blob/master/README.md Decimal.js replicates many methods from JavaScript's Number.prototype and Math objects for decimal arithmetic. ```javascript x = new Decimal(255.5) x.toExponential(5) // '2.55500e+2' x.toFixed(5) // '255.50000' x.toPrecision(5) // '255.50' Decimal.sqrt('6.98372465832e+9823') // '8.3568682281821340204e+4911' Decimal.pow(2, 0.0979843) // '1.0702770511687781839' // Using `toFixed()` to avoid exponential notation: x = new Decimal('0.0000001') x.toString() // '1e-7' x.toFixed() // '0.0000001' ``` -------------------------------- ### Basic Decimal Creation Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/decimal-constructor.md Create Decimal instances from numbers, strings, Decimal objects, and bigints. Strings are recommended for preserving precision. Verifies if created instances represent equivalent values. ```javascript const Decimal = require('decimal.js'); // From number const a = new Decimal(123.4567); // From string (recommended for precision) const b = new Decimal('123456.7e-3'); // From Decimal instance const c = new Decimal(a); // From bigint const d = new Decimal(9007199254740991n); // Equivalent values a.equals(b) && b.equals(c) && a.equals(c); // true ``` -------------------------------- ### Get the number of significant digits Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Returns the count of significant digits in the Decimal's value. Optionally includes trailing zeros in the integer part if `include_zeros` is true. ```javascript x = new Decimal(1.234) x.precision() ``` ```javascript y = new Decimal(987000) y.sd() ``` ```javascript y.sd(true) ``` -------------------------------- ### Decimal Conversion Methods Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/quick-reference.md Demonstrates converting Decimal instances to different formats such as strings, fixed-point, exponential, precision, numbers, fractions, binary, hexadecimal, and octal. ```javascript x.toString() x.toFixed(2) x.toExponential(2) x.toPrecision(4) x.toNumber() x.toFraction() x.toBinary() x.toHexadecimal() x.toOctal() ``` -------------------------------- ### Comparison and Conditionals with Decimal.js Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/getting-started.md Shows how to compare Decimal.js numbers using methods like lessThan, equals, and comparedTo, and use the results in conditional statements. ```javascript const Decimal = require('decimal.js'); const price = new Decimal('19.99'); const budget = new Decimal('20.00'); if (price.lessThan(budget)) { console.log('Can afford'); } if (price.equals(new Decimal('19.99'))) { console.log('Exact match'); } const comparison = price.comparedTo(budget); if (comparison < 0) { console.log('Less than'); } else if (comparison > 0) { console.log('Greater than'); } else { console.log('Equal'); } ``` -------------------------------- ### Decimal Creation of Special Values Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/decimal-constructor.md Demonstrates creating Decimal instances for special numeric values like Infinity, negative zero, and NaN. Includes checks for finiteness, string representation of negative zero, and NaN status. ```javascript const Decimal = require('decimal.js'); // Infinity const inf = new Decimal(Infinity); inf.isFinite(); // false // Negative zero const negZero = new Decimal(-0); negZero.toString(); // '-0' // NaN const nan = new Decimal(NaN); nan.isNaN(); // true ``` -------------------------------- ### Configuration Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/index.md Allows global configuration of Decimal.js settings such as precision and rounding modes, or creation of independent Decimal instances with custom configurations. ```APIDOC ## Configuration ### Description Customize the behavior of Decimal.js globally or for specific instances. This includes setting the default precision for calculations and the rounding mode to be used. ### Methods - **Decimal.set(config)**: Sets the global configuration for all Decimal instances. `config` is an object with properties like `precision` and `rounding`. - **Decimal.clone(config)**: Creates and returns a new Decimal constructor with its own independent configuration, specified by the `config` object. ### Configuration Options - **precision** (number): The number of significant digits to be used in arithmetic operations. Defaults to 20. - **rounding** (number): The rounding mode to be used. Defaults to `Decimal.ROUND_HALF_UP`. ### Examples ```javascript const Decimal = require('decimal.js'); // Set global configuration Decimal.set({ precision: 50, rounding: 4 }); // Create independent Decimal with different config const HighPrec = Decimal.clone({ precision: 100 }); const LowPrec = Decimal.clone({ precision: 5 }); const x = new Decimal(1).div(3); const y = new HighPrec(1).div(3); x.toString(); // 20 significant digits (default) y.toString(); // 100 significant digits ``` ``` -------------------------------- ### valueOf: Get Decimal Value as String Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Returns a string representation of the Decimal, similar to toString, but with a signed zero (-0) if applicable. This method is primarily for compatibility with JavaScript's Number.prototype.valueOf. ```javascript x = new Decimal(-0) x.valueOf() // '-0' ``` -------------------------------- ### Decimal Static Utility Methods Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/quick-reference.md Shows static methods for finding the maximum or minimum of multiple Decimal arguments, determining the sign of a number, generating a random Decimal, and checking if a value is a Decimal instance. ```javascript Decimal.max(a, b, c) Decimal.min(a, b, c) Decimal.sign(x) Decimal.random() Decimal.isDecimal(x) ``` -------------------------------- ### Default Configuration Object Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/index.md The default configuration settings for the Decimal.js library. ```javascript { precision: 20, rounding: 4, toExpNeg: -7, toExpPos: 21, minE: -9e15, maxE: 9e15, modulo: 1, crypto: false } ``` -------------------------------- ### Handle Multiple Precision Requirements with Cloned Constructors Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/configuration.md Demonstrates using `Decimal.clone()` to create constructors with different precision settings for specific calculation needs, such as high precision and display precision. ```javascript const Decimal = require('decimal.js'); // Global default Decimal.set({ precision: 20 }); // High precision for specific calculations const HighPrec = Decimal.clone({ precision: 100 }); // Low precision for display const Display = Decimal.clone({ precision: 2 }); const price = new Decimal('19.99'); const precise = new HighPrec(price); const display = new Display(price); precise.div(3).toString(); // Many significant digits display.div(3).toString(); // Just 2 significant digits ``` -------------------------------- ### Decimal.sign() - Get Sign of a Value Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/api-reference/static-methods.md Returns the sign of a Decimal value. The return value indicates whether the number is positive (1), negative (-1), zero (0), negative zero (-0), or not a number (NaN). ```javascript const Decimal = require('decimal.js'); Decimal.sign('5'); // 1 Decimal.sign('-5'); // -1 Decimal.sign('0'); // 0 Decimal.sign(NaN); // NaN ``` -------------------------------- ### Read Current Configuration Properties Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/configuration.md Access configuration settings directly as static properties on the Decimal constructor. These reflect the currently active configuration. ```javascript const Decimal = require('decimal.js'); console.log(Decimal.precision); // 20 console.log(Decimal.rounding); // 4 console.log(Decimal.toExpNeg); // -7 console.log(Decimal.toExpPos); // 21 console.log(Decimal.minE); // -9e15 console.log(Decimal.maxE); // 9e15 console.log(Decimal.modulo); // 1 console.log(Decimal.crypto); // false ``` -------------------------------- ### Decimal Exponential and Logarithm Operations Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/quick-reference.md Shows how to perform exponential and logarithm operations such as natural exponential (e^x), natural logarithm (ln(x)), and general logarithm (log(x)) with different bases. ```javascript x.exp() x.ln() x.log() x.log(2) x.log(10) ``` -------------------------------- ### Create Decimal Instances Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/index.md Instantiate Decimal objects from numbers, strings (recommended for precision), bigints, or other Decimal instances. Supports special values like Infinity and NaN, and base conversions from hex, binary, and octal. ```javascript const Decimal = require('decimal.js'); // From various types const a = new Decimal(123); // number const b = new Decimal('123.45'); // string (recommended) const c = new Decimal(123n); // bigint const d = new Decimal(a); // Decimal instance // Special values const inf = new Decimal(Infinity); const nan = new Decimal(NaN); const negZero = new Decimal(-0); // Base conversions const hex = new Decimal('0xFF'); // 255 const bin = new Decimal('0b1010'); // 10 const oct = new Decimal('0o77'); // 63 ``` -------------------------------- ### Import Minified ES Module Source: https://github.com/mikemcl/decimal.js/blob/master/README.md Import the minified ES module version of Decimal.js. ```javascript import Decimal from './decimal.min.mjs'; ``` -------------------------------- ### Default Configuration Object Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/configuration.md Displays the default configuration values used by Decimal.js if no custom settings are applied. ```json { "precision": 20, "rounding": 4, // ROUND_HALF_UP "toExpNeg": -7, "toExpPos": 21, "minE": -9e15, "maxE": 9e15, "modulo": 1, // DOWN "crypto": false } ``` -------------------------------- ### Decimal Initialization with Base Prefixes Source: https://github.com/mikemcl/decimal.js/blob/master/README.md Decimal instances can be initialized from strings representing binary, hexadecimal, or octal values by including the appropriate prefix. ```javascript x = new Decimal('0xff.f') // '255.9375' y = new Decimal('0b10101100') // '172' z = x.plus(y) // '427.9375' z.toBinary() // '0b110101011.1111' z.toBinary(13) // '0b1.101010111111p+8' // Using binary exponential notation to create a Decimal with the value of `Number.MAX_VALUE`. x = new Decimal('0b1.1111111111111111111111111111111111111111111111111111p+1023') // '1.7976931348623157081e+308' ``` -------------------------------- ### Import Decimal.js Constructor Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/index.md Import the Decimal constructor using CommonJS or ES Module syntax. ```javascript const Decimal = require('decimal.js'); ``` ```javascript import Decimal from 'decimal.js'; ``` ```javascript import { Decimal } from 'decimal.js'; ``` -------------------------------- ### Load Decimal.js in Node.js (ES Module) Source: https://github.com/mikemcl/decimal.js/blob/master/README.md Import the Decimal class from the decimal.js package using ES module syntax in Node.js. ```javascript import Decimal from 'decimal.js'; ``` -------------------------------- ### Configure Decimal.js Settings Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/types.md Use Decimal.set() to globally configure precision, rounding, exponential notation thresholds, and exponent boundaries. You can also clone Decimal with custom settings. ```javascript const Decimal = require('decimal.js'); // Set configuration Decimal.set({ precision: 50, rounding: Decimal.ROUND_HALF_EVEN, toExpNeg: -10, toExpPos: 25, maxE: 1000, minE: -1000 }); // Create custom Decimal with high precision const HighPrecision = Decimal.clone({ precision: 100, defaults: false // Inherit other settings from parent }); ``` -------------------------------- ### Configure for Financial Calculations Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/configuration.md Sets Decimal.js configuration suitable for financial calculations, emphasizing standard rounding and sufficient precision. ```javascript const Decimal = require('decimal.js'); Decimal.set({ precision: 28, // Sufficient for most currencies rounding: Decimal.ROUND_HALF_UP, // Standard rounding modulo: 1 // JavaScript-like behavior }); ``` -------------------------------- ### Scientific Calculations with Decimal.js Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/getting-started.md Demonstrates calculating mathematical constants like e and pi, and handling large scientific numbers using Decimal.js. ```javascript const Decimal = require('decimal.js'); // Calculate e (Euler's number) const e = new Decimal(1).exp(); console.log(e.toString()); // '2.718281828459045...' // Calculate pi const pi = Decimal.acos(-1); console.log(pi.toString()); // '3.141592653589793...' // Scientific constant const avogadro = new Decimal('6.02214076e23'); console.log(avogadro.toString()); ``` -------------------------------- ### Static vs Instance Method Comparison Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Compares the results of using static methods (e.g., Decimal.abs(x)) versus instance methods (e.g., new Decimal(x).abs()). ```javascript a = Decimal.abs(x) b = new Decimal(x).abs() a.equals(b) // true ``` ```javascript a = Decimal.acos(x) b = new Decimal(x).acos() a.equals(b) // true ``` ```javascript a = Decimal.acosh(x) b = new Decimal(x).acosh() a.equals(b) // true ``` ```javascript a = Decimal.add(x, y) b = new Decimal(x).plus(y) a.equals(b) // true ``` ```javascript a = Decimal.asin(x) b = new Decimal(x).asin() a.equals(b) // true ``` ```javascript a = Decimal.asinh(x) b = new Decimal(x).asinh() a.equals(b) // true ``` ```javascript a = Decimal.atan(x) b = new Decimal(x).atan() a.equals(b) // true ``` ```javascript a = Decimal.atanh(x) b = new Decimal(x).atanh() a.equals(b) // true ``` ```javascript a = Decimal.cbrt(x) b = new Decimal(x).cbrt() a.equals(b) // true ``` ```javascript a = Decimal.ceil(x) b = new Decimal(x).ceil() a.equals(b) // true ``` -------------------------------- ### Rounding and Formatting with Decimal.js Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/getting-started.md Shows how to round numbers to a specific number of decimal places, format them using fixed-point or exponential notation, and control significant digits. ```javascript const Decimal = require('decimal.js'); const price = new Decimal('19.995'); // Round to 2 decimal places console.log(price.toDP(2).toString()); // '20.00' console.log(price.toDP(2, Decimal.ROUND_DOWN).toString()); // '19.99' // Fixed-point formatting console.log(price.toFixed(2)); // '20.00' // Exponential notation console.log(price.toExponential(2)); // '2.00e+1' // Significant digits console.log(price.toPrecision(3)); // '20.0' ``` -------------------------------- ### Chain Configuration Calls Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/configuration.md The `Decimal.set()` method returns the constructor, allowing for chained calls to modify configuration sequentially. ```javascript // Chain calls Decimal.set({ precision: 30 }) .set({ rounding: 4 }) .set({ maxE: 500 }); ``` -------------------------------- ### Set Global and Clone Constructors Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/configuration.md Configure the default Decimal constructor globally or create independent constructors with specific settings using clone. ```javascript const Decimal = require('decimal.js'); // Global configuration Decimal.set({ precision: 50, rounding: 4 }); // Create independent constructor with different config const QuickCalc = Decimal.clone({ precision: 10 }); ``` -------------------------------- ### min Source: https://github.com/mikemcl/decimal.js/blob/master/doc/API.html Returns the minimum of the provided arguments. ```APIDOC ## min ### Description Returns the minimum of the provided arguments. ### Method `min(x [, y, ...])` ### Parameters - `x` (number|string|bigInt|Decimal) - The first value. - `y` (number|string|bigInt|Decimal) - The second value. - `...` - Additional values. ### Returns Decimal - The minimum value among the arguments. ### Example ```javascript r = Decimal.min(x, y, z) ``` ``` -------------------------------- ### Set Decimal.js Configuration Source: https://github.com/mikemcl/decimal.js/blob/master/_autodocs/quick-reference.md Use Decimal.set() to configure global precision and rounding. Use Decimal.config() for specific rounding modes. ```javascript Decimal.set({ precision: 50, rounding: 4 }); Decimal.config({ rounding: Decimal.ROUND_HALF_UP }); ```