Decimal
The Decimal class provides arbitrary precision decimal numbers, essential for financial calculations and applications where floating-point precision errors are unacceptable.
Import:
import { Decimal } from 'surrealdb';
Source: value/decimal.ts
Why Use Decimal?
JavaScript’s number type uses floating-point arithmetic, which can lead to precision errors:
console.log(0.1 + 0.2);
const a = new Decimal('0.1');
const b = new Decimal('0.2');
console.log(a.plus(b).toString());
Constructor
new Decimal(value)
Create a new arbitrary precision decimal.
Syntax
new Decimal(decimal)
new Decimal(string)
new Decimal(number | bigint)
new Decimal([int, frac, scale])
Parameters
| Parameter | Type | Description |
|---|
value required | Decimal | string | number | bigint | [bigint, bigint, number] | Value to create decimal from. |
Examples
const price = new Decimal('19.99');
const precise = new Decimal('0.123456789012345678901234567890');
const value = new Decimal(19.99);
const large = new Decimal(1000000n);
const scientific = new Decimal('1.23e-10');
const copy = new Decimal(price);
Static Methods
Decimal.parse(string)
Parse a decimal from a string.
Syntax
Decimal.parse(str)
Returns
Decimal - Parsed decimal
Example
const price = Decimal.parse('19.99');
const percentage = Decimal.parse('0.075');
Instance Methods
.toString()
Convert to string representation (preserves precision).
Syntax
decimal.toString()
Returns
string - String representation
Example
const price = new Decimal('19.99');
console.log(price.toString());
const precise = new Decimal('0.123456789012345678901234567890');
console.log(precise.toString());
.toNumber()
Convert to JavaScript number.
Syntax
decimal.toNumber()
Returns
number - JavaScript number (may lose precision)
Converting to number may lose precision for very large or very precise values.
Example
const price = new Decimal('19.99');
const num = price.toNumber();
const precise = new Decimal('0.123456789012345678901234567890');
const lost = precise.toNumber();
.toJSON()
Serialize for JSON.
Syntax
decimal.toJSON()
Returns
string - String representation for JSON
.plus(other)
Add another decimal.
Syntax
decimal.plus(other)
Parameters
| Parameter | Type | Description |
|---|
other required | Decimal | string | number | Value to add. |
Returns
Decimal - Sum
Example
const price1 = new Decimal('19.99');
const price2 = new Decimal('5.50');
const total = price1.plus(price2);
console.log(total.toString());
.minus(other)
Subtract another decimal.
Syntax
decimal.minus(other)
Returns
Decimal - Difference
.times(other)
Multiply by another decimal.
Syntax
decimal.times(other)
Returns
Decimal - Product
Example
const price = new Decimal('19.99');
const quantity = new Decimal('3');
const total = price.times(quantity);
console.log(total.toString());
.dividedBy(other)
Divide by another decimal.
Syntax
decimal.dividedBy(other)
Returns
Decimal - Quotient
.equals(other)
Check if two decimals are equal.
Syntax
decimal.equals(other)
Returns
boolean - True if equal
Complete Examples
Financial Calculations
import { Surreal, Decimal, Table } from 'surrealdb';
const db = new Surreal();
await db.connect('ws://localhost:8000');
const product = await db.create(new Table('products')).content({
name: 'Widget',
price: new Decimal('19.99'),
tax_rate: new Decimal('0.075')
});
const price = new Decimal(product.price);
const taxRate = new Decimal(product.tax_rate);
const tax = price.times(taxRate);
const total = price.plus(tax);
console.log('Price:', price.toString());
console.log('Tax:', tax.toString());
console.log('Total:', total.toString());
Order Total Calculation
interface OrderItem {
product: string;
price: Decimal;
quantity: number;
}
function calculateOrderTotal(items: OrderItem[]): Decimal {
let total = new Decimal('0');
for (const item of items) {
const itemTotal = item.price.times(item.quantity);
total = total.plus(itemTotal);
}
return total;
}
const items = [
{ product: 'Widget', price: new Decimal('19.99'), quantity: 2 },
{ product: 'Gadget', price: new Decimal('29.99'), quantity: 1 },
{ product: 'Tool', price: new Decimal('9.99'), quantity: 3 }
];
const orderTotal = calculateOrderTotal(items);
console.log('Order total:', orderTotal.toString());
Currency Exchange
const usdAmount = new Decimal('100.00');
const exchangeRate = new Decimal('1.18');
const eurAmount = usdAmount.times(exchangeRate);
console.log(`$${usdAmount} = €${eurAmount}`);
Interest Calculation
function calculateCompoundInterest(
principal: Decimal,
rate: Decimal,
periods: number
): Decimal {
let amount = principal;
const onePlusRate = new Decimal('1').plus(rate);
for (let i = 0; i < periods; i++) {
amount = amount.times(onePlusRate);
}
return amount;
}
const principal = new Decimal('1000.00');
const annualRate = new Decimal('0.05');
const years = 10;
const finalAmount = calculateCompoundInterest(principal, annualRate, years);
console.log('Final amount:', finalAmount.toString());
Database Storage
const transaction = await db.create(new Table('transactions')).content({
user: userId,
amount: new Decimal('149.99'),
fee: new Decimal('2.50'),
tax: new Decimal('11.25'),
timestamp: DateTime.now()
});
const transactions = await db.select(new Table('transactions'));
let totalAmount = new Decimal('0');
for (const txn of transactions) {
totalAmount = totalAmount.plus(txn.amount);
}
console.log('Total:', totalAmount.toString());
Percentage Calculations
function calculatePercentage(value: Decimal, percentage: Decimal): Decimal {
return value.times(percentage).dividedBy(new Decimal('100'));
}
const price = new Decimal('100.00');
const discount = new Decimal('15');
const discountAmount = calculatePercentage(price, discount);
const finalPrice = price.minus(discountAmount);
console.log('Discount:', discountAmount.toString());
console.log('Final price:', finalPrice.toString());
Scientific Calculations
const avogadroNumber = new Decimal('6.02214076e23');
const boltzmannConstant = new Decimal('1.380649e-23');
console.log('Avogadro:', avogadroNumber.toString());
console.log('Boltzmann:', boltzmannConstant.toString());
Best Practices
const price = new Decimal('19.99');
const price = new Decimal(19.99);
2. Keep as Decimal for Calculations
const subtotal = price.times(quantity);
const tax = subtotal.times(taxRate);
const total = subtotal.plus(tax);
const subtotal = price.toNumber() * quantity;
3. Convert to String for Display
const display = price.toString();
console.log(`$${display}`);
const display = price.toNumber().toFixed(2);
4. Store Decimals in Database
await db.create(table).content({
price: new Decimal('19.99')
});
await db.create(table).content({
price: 19.99
});
Common Pitfalls
const wrong = new Decimal(0.1 + 0.2);
const correct = new Decimal('0.1').plus(new Decimal('0.2'));
Premature Conversion to Number
const result = price.toNumber() + tax.toNumber();
const result = price.plus(tax);
See Also