Mastering Currency.js with TypeScript

In the realm of web development, handling currency values accurately is of utmost importance. Incorrect handling of currency can lead to financial discrepancies, which is a serious issue in any application dealing with money. currency.js is a lightweight JavaScript library that simplifies currency management by providing a reliable way to perform arithmetic operations on currency values while avoiding common floating - point errors. When combined with TypeScript, it offers static type checking, enhancing code reliability and maintainability. This blog post will guide you through the fundamental concepts, usage methods, common practices, and best practices of using currency.js with TypeScript.

Table of Contents

  1. Fundamental Concepts
  2. Installation
  3. Usage Methods
  4. Common Practices
  5. Best Practices
  6. Conclusion
  7. References

Fundamental Concepts

Floating - Point Errors

JavaScript uses the IEEE 754 standard to represent floating - point numbers. This can lead to precision issues when performing arithmetic operations on decimal numbers. For example:

const result = 0.1 + 0.2;
console.log(result); // Outputs: 0.30000000000000004

This is a problem when dealing with currency, as even a small error can cause significant financial discrepancies.

currency.js Basics

currency.js wraps around a number and provides methods to perform arithmetic operations without floating - point errors. It stores the currency value as an integer under the hood, which allows for accurate calculations.

TypeScript Integration

TypeScript adds static type checking to JavaScript. When using currency.js with TypeScript, you can define types for currency values, ensuring that the operations are performed on valid currency objects.

Installation

First, you need to install currency.js in your project. You can use npm or yarn:

npm install currency.js
# or
yarn add currency.js

If you are using TypeScript, you also need to install the type definitions. They are usually included in the package, but in some cases, you might need to install them separately:

npm install --save-dev @types/currency.js
# or
yarn add --dev @types/currency.js

Usage Methods

Creating a Currency Object

import currency from 'currency.js';

// Create a currency object with a value
const price = currency(10.99);
console.log(price.value); // Outputs: 10.99

Performing Arithmetic Operations

import currency from 'currency.js';

const price = currency(10.99);
const tax = currency(0.99);

// Addition
const total = price.add(tax);
console.log(total.value); // Outputs: 11.98

// Subtraction
const afterDiscount = total.subtract(currency(1));
console.log(afterDiscount.value); // Outputs: 10.98

// Multiplication
const quantity = 3;
const totalForThree = afterDiscount.multiply(quantity);
console.log(totalForThree.value); // Outputs: 32.94

// Division
const perItem = totalForThree.divide(quantity);
console.log(perItem.value); // Outputs: 10.98

Formatting Currency

import currency from 'currency.js';

const price = currency(10.99);
const formatted = price.format();
console.log(formatted); // Outputs: $10.99

Common Practices

Error Handling

When performing arithmetic operations, currency.js can throw errors if the input is invalid. You should handle these errors gracefully in your code.

import currency from 'currency.js';

try {
    const invalidValue = currency('abc');
} catch (error) {
    console.error('Invalid currency value:', error);
}

Working with Different Currencies

currency.js is mainly focused on numerical operations. If you need to work with different currencies, you can create a wrapper function to handle currency conversion and formatting.

import currency from 'currency.js';

interface CurrencyOptions {
    symbol: string;
    decimal: string;
    separator: string;
}

function createCurrency(value: number, options: CurrencyOptions) {
    return currency(value, {
        symbol: options.symbol,
        decimal: options.decimal,
        separator: options.separator
    });
}

const euroOptions: CurrencyOptions = {
    symbol: '€',
    decimal: ',',
    separator: '.'
};

const euroPrice = createCurrency(10.99, euroOptions);
console.log(euroPrice.format()); // Outputs: €10,99

Best Practices

Use Constants for Currency Values

Instead of hard - coding currency values throughout your code, use constants. This makes the code more maintainable and easier to update if the values change.

import currency from 'currency.js';

const TAX_RATE = currency(0.08);
const PRICE = currency(20);

const total = PRICE.add(PRICE.multiply(TAX_RATE));
console.log(total.value);

Type Definitions for Currency Objects

In TypeScript, define custom types for currency objects to make the code more self - explanatory and easier to understand.

import currency from 'currency.js';

type CurrencyValue = ReturnType<typeof currency>;

function calculateTotal(price: CurrencyValue, tax: CurrencyValue): CurrencyValue {
    return price.add(tax);
}

const price = currency(10.99);
const tax = currency(0.99);
const total = calculateTotal(price, tax);
console.log(total.value);

Conclusion

currency.js is a powerful and lightweight library for handling currency values in JavaScript applications. When combined with TypeScript, it becomes even more robust, offering static type checking and better code organization. By understanding the fundamental concepts, using the provided usage methods, following common practices, and implementing best practices, you can ensure accurate and reliable currency handling in your projects.

References