Precision arithmetic provides high-precision mathematical operations for accurate financial calculations without floating-point errors. The Precise class handles large numbers and decimal operations with exact precision, essential for cryptocurrency and financial applications.
Create high-precision numbers from strings or regular numbers.
/**
* Create a Precise number instance
*/
class Precise {
constructor(number: bigint | string, decimals?: number);
/** Internal representation */
decimals: number;
integer: bigint;
base: any;
}Usage Examples:
import { Precise } from 'ccxt';
// Create from string (recommended for precision)
const price = new Precise('123.456789');
const amount = new Precise('0.00123456789');
// Create from number (may lose precision)
const simple = new Precise(123.45);
// Create with explicit decimal places
const scaled = new Precise('123456789', 6); // Represents 123.456789
console.log(price.toString()); // '123.456789'
console.log(amount.toString()); // '0.00123456789'
console.log(scaled.toString()); // '123.456789'Perform precise arithmetic operations without floating-point errors.
/**
* Arithmetic operations on Precise numbers
*/
interface Precise {
/** Multiply two Precise numbers */
mul(other: Precise): Precise;
/** Divide two Precise numbers with optional precision */
div(other: Precise, precision?: number): Precise;
/** Add two Precise numbers */
add(other: Precise): Precise;
/** Subtract two Precise numbers */
sub(other: Precise): Precise;
/** Modulo operation */
mod(other: Precise): Precise;
/** Absolute value */
abs(): Precise;
/** Negate the number */
neg(): Precise;
/** Bitwise OR operation */
or(other: Precise): Precise;
}Usage Examples:
import { Precise } from 'ccxt';
const price = new Precise('50000.123456');
const amount = new Precise('0.00123456');
const fee = new Precise('0.001');
// Multiplication (calculate cost)
const cost = price.mul(amount);
console.log(`Cost: ${cost.toString()}`); // Exact: 61.728395061888
// Division
const pricePerUnit = cost.div(amount);
console.log(`Price per unit: ${pricePerUnit.toString()}`); // Back to original price
// Addition (add fee)
const totalCost = cost.add(fee);
console.log(`Total with fee: ${totalCost.toString()}`);
// Subtraction
const netCost = totalCost.sub(fee);
console.log(`Net cost: ${netCost.toString()}`);
// Chain operations
const finalAmount = price
.mul(amount)
.add(fee)
.mul(new Precise('1.01')); // Add 1% markup
console.log(`Final amount: ${finalAmount.toString()}`);Compare Precise numbers for ordering and equality.
/**
* Comparison operations
*/
interface Precise {
/** Greater than */
gt(other: Precise): boolean;
/** Greater than or equal */
ge(other: Precise): boolean;
/** Less than */
lt(other: Precise): boolean;
/** Less than or equal */
le(other: Precise): boolean;
/** Equality check */
equals(other: any): boolean;
/** Find minimum of two values */
min(other: Precise): Precise;
/** Find maximum of two values */
max(other: Precise): Precise;
}Usage Examples:
import { Precise } from 'ccxt';
const price1 = new Precise('50000.123456');
const price2 = new Precise('50000.123457');
const zero = new Precise('0');
// Comparisons
console.log(price1.lt(price2)); // true
console.log(price1.equals(price2)); // false
console.log(price1.gt(zero)); // true
// Min/max operations
const minPrice = price1.min(price2);
const maxPrice = price1.max(price2);
console.log(`Min: ${minPrice.toString()}`); // 50000.123456
console.log(`Max: ${maxPrice.toString()}`); // 50000.123457
// Conditional logic
const targetPrice = new Precise('50000');
if (price1.gt(targetPrice)) {
console.log('Price is above target');
}
// Find best price
const prices = [
new Precise('50000.123'),
new Precise('49999.987'),
new Precise('50001.456'),
];
let bestPrice = prices[0];
for (const price of prices.slice(1)) {
bestPrice = bestPrice.min(price);
}
console.log(`Best price: ${bestPrice.toString()}`);Convert Precise numbers to strings and handle formatting.
/**
* String conversion and utility methods
*/
interface Precise {
/** Convert to string representation */
toString(): string;
/** Reduce precision by removing trailing zeros */
reduce(): this;
}Usage Examples:
import { Precise } from 'ccxt';
// String conversion
const amount = new Precise('123.456000');
console.log(amount.toString()); // '123.456000'
// Reduce trailing zeros
const reduced = amount.reduce();
console.log(reduced.toString()); // '123.456'
// Formatting for display
function formatCurrency(precise, currency) {
return `${precise.toString()} ${currency}`;
}
const balance = new Precise('1234.56789');
console.log(formatCurrency(balance, 'BTC')); // '1234.56789 BTC'
// Scientific notation handling
const largeNumber = new Precise('123456789012345.123');
console.log(largeNumber.toString()); // Exact representation without scientific notationPerform arithmetic operations directly on string representations.
/**
* Static methods for string-based arithmetic
*/
interface PreciseStatic {
/** String multiplication */
stringMul(string1: string, string2: string): string;
/** String division with precision */
stringDiv(string1: string, string2: string, precision?: number): string;
/** String addition */
stringAdd(string1: string, string2: string): string;
/** String subtraction */
stringSub(string1: string, string2: string): string;
/** String absolute value */
stringAbs(string: string): string;
/** String negation */
stringNeg(string: string): string;
/** String modulo */
stringMod(string1: string, string2: string): string;
/** String bitwise OR */
stringOr(string1: string, string2: string): string;
/** String equality */
stringEquals(string1: string, string2: string): boolean;
stringEq(string1: string, string2: string): boolean;
/** String minimum */
stringMin(string1: string, string2: string): string;
/** String maximum */
stringMax(string1: string, string2: string): string;
/** String comparisons */
stringGt(string1: string, string2: string): boolean;
stringGe(string1: string, string2: string): boolean;
stringLt(string1: string, string2: string): boolean;
stringLe(string1: string, string2: string): boolean;
}Usage Examples:
import { Precise } from 'ccxt';
// Direct string operations (useful for performance-critical code)
const result1 = Precise.stringMul('123.456', '0.789');
console.log(result1); // '97.448784'
const result2 = Precise.stringAdd('100.001', '200.002');
console.log(result2); // '300.003'
const result3 = Precise.stringDiv('100', '3', 6);
console.log(result3); // '33.333333'
// String comparisons
console.log(Precise.stringGt('123.456', '123.455')); // true
console.log(Precise.stringEquals('100.000', '100')); // false (different precision)
// Utility functions
function calculatePortfolioValue(holdings) {
let total = '0';
for (const holding of holdings) {
const value = Precise.stringMul(holding.amount, holding.price);
total = Precise.stringAdd(total, value);
}
return total;
}
const portfolio = [
{ amount: '1.5', price: '50000' },
{ amount: '10.0', price: '3000' },
{ amount: '100.0', price: '1' },
];
const totalValue = calculatePortfolioValue(portfolio);
console.log(`Portfolio value: $${totalValue}`); // Exact calculationCommon financial calculations using Precise arithmetic.
/**
* Financial calculation patterns using Precise
*/
interface FinancialCalculations {
calculateOrderCost(amount: string, price: string): string;
calculateFee(cost: string, feeRate: string): string;
calculateTotal(cost: string, fee: string): string;
calculatePnL(entryPrice: string, exitPrice: string, amount: string): string;
calculatePercentageChange(oldValue: string, newValue: string): string;
}Usage Examples:
import { Precise } from 'ccxt';
// Order cost calculation
function calculateOrderTotal(amount, price, feeRate) {
const cost = new Precise(amount).mul(new Precise(price));
const fee = cost.mul(new Precise(feeRate));
const total = cost.add(fee);
return {
cost: cost.toString(),
fee: fee.toString(),
total: total.toString(),
};
}
const order = calculateOrderTotal('0.1', '50000', '0.001');
console.log(`Cost: $${order.cost}`);
console.log(`Fee: $${order.fee}`);
console.log(`Total: $${order.total}`);
// PnL calculation
function calculatePnL(entryPrice, exitPrice, amount, side) {
const entry = new Precise(entryPrice);
const exit = new Precise(exitPrice);
const qty = new Precise(amount);
let pnl;
if (side === 'long') {
pnl = exit.sub(entry).mul(qty);
} else {
pnl = entry.sub(exit).mul(qty);
}
return pnl.toString();
}
const longPnL = calculatePnL('50000', '51000', '0.1', 'long');
console.log(`Long PnL: $${longPnL}`); // Profit: $100
// Percentage change
function calculatePercentageChange(oldValue, newValue) {
const old = new Precise(oldValue);
const current = new Precise(newValue);
const change = current.sub(old);
const percentage = change.div(old).mul(new Precise('100'));
return percentage.toString();
}
const change = calculatePercentageChange('50000', '51000');
console.log(`Change: ${change}%`); // 2%