exframe-decimal
v1.0.3
Published
exframe-decimal description
Downloads
170
Readme
Decimal Class
The Decimal class is designed for precise handling of decimal values in JavaScript. It uses BigInt and other mathematical operations to ensure accuracy and avoid common issues with floating-point arithmetic.
Installation
npm install exframe-decimal
Usage
import Decimal from 'decimal-class';
// Create a decimal instance
const decimal = new Decimal(1.23);
// Perform arithmetic operations
const sum = decimal.add(2.45);
const product = decimal.multiply(3.14);
const quotient = decimal.divide(0.5);
const difference = decimal.subtract(0.8);
// Convert decimal to other types
const numberValue = decimal.toNumber();
const stringValue = decimal.toString();
// Specify precision
const rounded = decimal.toDecimalPlaces(2);
// Get absolute value
const absoluteValue = decimal.absolute();
API
new Decimal(value, options?)
Create an instance of the Decimal class. The class is immutable, all operations will return a new insatnce of the Decimal class.
| Parameter | Type | Description |
|-----------|-------------------------------|-------------------------------------------------------------|
| value
| Number \| Decimal \| String
| The decimal value. |
| options
| { precision: Number = 4 }?
| Optional options to configure the precision of the Decimal. |
multiply(decimal: Decimal)
Returns the product of the multiplication of the current and the given Decimal values.
| Parameter | Type | Description |
|-----------|----------|--------------------------|
| decimal
| Decimal
| The second operand. |
divide(decimal: Decimal)
Returns the quotient of the division of the current and the given Decimal values.
| Parameter | Type | Description |
|-----------|----------|--------------------------|
| decimal
| Decimal
| The second operand. |
add(decimal: Decimal)
Returns the sum of the addition of the current and the given Decimal values.
| Parameter | Type | Description |
|-----------|----------|--------------------------|
| decimal
| Decimal
| The second operand. |
subtract(decimal: Decimal)
Returns the difference of the subtraction of the current and the given Decimal values.
| Parameter | Type | Description |
|-----------|----------|--------------------------|
| decimal
| Decimal
| The second operand. |
toDecimalPlaces(precision?: Number, options?)
Rounds the current value to the desired precision. If the value is greater than the current precision, it multiplies by 10^difference.
| Parameter | Type | Description |
|------------|----------|------------------------------------------------------------------------------|
| precision
| Number
| The desired precision. |
| options
| { truncate: Boolean = false }?
| Optional options to configure the rounding behavior. |
truncate()
Truncates the current value to a precision of 0.
absolute()
Returns the absolute value of the current decimal value.
negative()
Returns the inverse of the current decimal value.