Senior LevelExpress JS
How do you prevent floating-point precision errors in Express e-commerce checkout APIs?
❓ Interview Prompt: Explain IEEE 754 floating-point rounding errors (0.1 + 0.2 !== 0.3), integer cents representation, and decimal precision libraries.
Native JavaScript Numbers use IEEE 754 double-precision floating-point arithmetic. Calculating '0.1 + 0.2' evaluates to '0.30000000000000004'! Using float arithmetic for currency in e-commerce checkout APIs causes rounding bugs and accounting discrepancies.
Solutions:
1
Integer Cents: Represent all currency as integers in the smallest currency unit (e.g. '$10.99' stored as '1099' cents).
2
Decimal Libraries: Use 'decimal.js' or 'currency.js' for arbitrary-precision decimal operations and map to PostgreSQL 'NUMERIC(12,4)' columns.
Code Implementation Example
javascript
import express from 'express';
import currency from 'currency.js';
const app = express();
app.post('/api/checkout', (req, res) => {
// ❌ DANGEROUS: Float math causes rounding errors! (10.99 * 1.08 = 11.869200000000001)
// const total = req.body.price * 1.08;
// ✅ SECURE: Currency.js precise decimal arithmetic
const price = currency(req.body.price);
const total = price.multiply(1.08); // Returns exact currency format: $11.87
res.json({ totalCents: total.intValue, formatted: total.format() });
});💡Executing precise currency calculations using currency.js.
🎯 Interview Key Takeaway
Never use native float math for currency in Express APIs. Represent money as integer cents or use currency.js.
#Currency#Precision#E-Commerce#Senior
Back to all Express JS Questions→