Skip to content

Latest commit

 

History

History
68 lines (53 loc) · 2.17 KB

File metadata and controls

68 lines (53 loc) · 2.17 KB
title Work with Arbitrary-Precision Numbers using BigDecimal
id data-bigdecimal
skillLevel intermediate
applicationPatternId core-concepts
summary Use BigDecimal for arbitrary-precision decimal arithmetic, avoiding rounding errors and loss of precision in financial or scientific calculations.
tags
BigDecimal
numeric
precision
decimal
data-type
effect
rule
description
Use BigDecimal to represent and compute with decimal numbers that require arbitrary precision, such as in finance or scientific domains.
related
use-chunk-for-high-performance-collections
data-struct
author PaulJPhilp
lessonOrder 21

Work with Arbitrary-Precision Numbers using BigDecimal

Guideline

Use the BigDecimal data type for decimal numbers that require arbitrary precision, such as financial or scientific calculations.
This avoids rounding errors and loss of precision that can occur with JavaScript's native number type.

Rationale

JavaScript's number type is a floating-point double, which can introduce subtle bugs in calculations that require exact decimal representation.
BigDecimal provides precise, immutable arithmetic for critical domains.

Good Example

import { BigDecimal } from "effect";

// Create BigDecimal values
const a = BigDecimal.fromNumber(0.1);
const b = BigDecimal.fromNumber(0.2);

// Add, subtract, multiply, divide
const sum = BigDecimal.sum(a, b); // BigDecimal(0.3)
const product = BigDecimal.multiply(a, b); // BigDecimal(0.02)

// Compare values
const isEqual = BigDecimal.equals(sum, BigDecimal.fromNumber(0.3)); // true

// Convert to string or number
const asString = BigDecimal.format(BigDecimal.normalize(sum)); // "0.3"
const asNumber = BigDecimal.unsafeToNumber(sum); // 0.3

Explanation:

  • BigDecimal is immutable and supports precise decimal arithmetic.
  • Use it for domains where rounding errors are unacceptable (e.g., finance, billing, scientific data).
  • Avoids the pitfalls of floating-point math in JavaScript.

Anti-Pattern

Using JavaScript's native number type for financial or scientific calculations, which can lead to rounding errors and loss of precision.