Currency.js - Financial Calculations

2.0.4 · active · verified Sun Apr 19

currency.js is a lightweight JavaScript library specifically designed for accurate financial calculations and handling currency values, aiming to circumvent common floating-point precision issues inherent in JavaScript's number type. The current stable version is 2.0.4, with recent releases primarily focusing on critical bug fixes related to the `fromCents` option and minor security updates to development dependencies. The library provides a simple, fluent API for creating currency objects, performing arithmetic operations (add, subtract, multiply, divide), and robust formatting capabilities. It supports various international currency formats, custom patterns, and precision settings, making it a suitable choice for applications requiring reliable money management without the overhead of larger, more complex financial libraries. Its key differentiator is its small footprint and dedicated focus on fixed-point arithmetic for ensuring precision in monetary calculations.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic instantiation, arithmetic operations, custom formatting, and handling values explicitly as cents.

import currency from 'currency.js';

// Create a currency object
const price = currency(1234.56);

// Perform arithmetic operations
const tax = price.multiply(0.0825); // Calculate 8.25% tax
const shipping = currency(15.99);
const total = price.add(tax).add(shipping);

console.log(`Original Price: ${price.format()}`);
console.log(`Tax Amount: ${tax.format()}`);
console.log(`Shipping Cost: ${shipping.format()}`);
console.log(`Total Amount: ${total.format()}`);

// Using custom options
const euroPrice = currency(100.50, { symbol: '€', separator: '.', decimal: ',' });
const discount = currency(10, { symbol: '€', separator: '.', decimal: ',' });
const finalEuroPrice = euroPrice.subtract(discount);

console.log(`Euro Price: ${euroPrice.format()}`);
console.log(`Final Euro Price after discount: ${finalEuroPrice.format()}`);

// Handling values as cents
const valueInCents = currency(2500, { fromCents: true }); // Represents $25.00
console.log(`Value from cents: ${valueInCents.format()}`);

view raw JSON →