| 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 |
|
||||||
| rule |
|
||||||
| related |
|
||||||
| author | PaulJPhilp | ||||||
| lessonOrder | 21 |
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.
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.
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.3Explanation:
BigDecimalis 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.
Using JavaScript's native number type for financial or scientific calculations, which can lead to rounding errors and loss of precision.