惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
罗磊的独立博客
The GitHub Blog
The GitHub Blog
V
V2EX
Last Week in AI
Last Week in AI
博客园 - 聂微东
MyScale Blog
MyScale Blog
美团技术团队
L
LangChain Blog
博客园 - Franky
腾讯CDC
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园_首页
S
SegmentFault 最新的问题
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Stack Overflow Blog
Stack Overflow Blog
量子位
小众软件
小众软件
宝玉的分享
宝玉的分享
J
Java Code Geeks
Google DeepMind News
Google DeepMind News
D
Docker
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Represent Money in Software
Doogal Simpson · 2026-06-23 · via DEV Community

Quick Answer: Never use floating-point numbers to represent money in software. Because floating-point math cannot perfectly represent base-10 decimals, it introduces microscopic inaccuracies that compound over time. I recommend using either a dedicated arbitrary-precision decimal library or storing currency as integers representing micro-units to guarantee exact calculations.

If I ask you how to represent £1.29 in code, your naive first instinct might be to just drop it into a floating-point variable. I see this often, but if you start representing money as floating points, you are going to introduce systemic inaccuracies into your application. If there is one thing I know for sure, it's that people really don't like having inaccuracies anywhere close to their money. Let's look at why this happens and what you should do instead.

Why do floating-point numbers fail for currency calculations?

Floating-point numbers fail because they use binary fractions to approximate base-10 decimals, meaning simple arithmetic often yields imprecise results. When you execute a long sequence of these operations, those tiny inaccuracies compound into real financial errors.

I have a whole other video on why 0.1 + 0.2 doesn't equal 0.3 in most programming languages, but it's the classic example of this problem. If you run that calculation using standard floating-point operations, you'll get something like 0.30000000000000004.

// This is why floats and money don't mix
const itemOne = 0.1;
const itemTwo = 0.2;
console.log(itemOne + itemTwo === 0.3); // Evaluates to false

If your business logic relies on checking if those two items total exactly 0.3, the code evaluates to false. Do this thousands of times across a financial system, and those compounding rounding errors eventually change the amount of money a user actually has.

What are the best methods to handle money in programming?

The two reliable methods for handling money are using an arbitrary-precision decimal library or representing the currency as an integer. Decimal libraries give you exact math natively, while the integer method relies on fast, reliable whole-number operations.

Most modern languages include built-in libraries capable of doing accurate decimal operations. These are great because they solve the problem entirely at the language level. However, they can be somewhat heavyweight and a bit slower to execute. If you want an alternative that keeps things lightweight and fast, you can use integers instead.

Here is how the two viable strategies compare:

  • Built-in Decimal Libraries: Provide perfect mathematical accuracy and high readability, but are heavier in memory and slower for the CPU to compute.
  • Integer Representation: Extremely fast for the CPU to process and highly accurate, but requires manual mathematical scaling logic before rendering values to the UI.

How do you implement the integer micro-unit pattern?

To use the integer micro-unit pattern, you multiply the currency value by a large factor—like 100,000—so you only perform arithmetic on whole numbers. This pushes any unavoidable rounding errors from division operations so far down the decimal chain that they become completely irrelevant.

Your first thought might be to just store pence or cents. So, instead of 1.29, you store 129. That works perfectly for basic addition and subtraction. However, as soon as you need to divide a bill or calculate a percentage, you get rounding errors on the penny.

Instead, I recommend scaling the value up further into micro-units. For example, you represent £1.29 as 129,000. Adding and subtracting remains pure, fast integer math. If you eventually hit a rounding error during a complex division step, that error happens at such a microscopic decimal place that you simply don't care. Everything works, and your users' balances remain accurate.

Frequently Asked Questions

Should I use a standard Decimal library or integers for my project?

If your application doesn't have extreme performance constraints, I recommend sticking to your language's built-in Decimal library for safety and readability. Use integer micro-units if you are optimizing for processing speed or working in a highly distributed system where payload size matters.

How do databases typically store money values?

Most relational databases offer a DECIMAL or NUMERIC column type designed specifically for exact precision. If you use the integer micro-unit pattern in your application, you can simply store those scaled values in a standard BIGINT database column.

What happens to fractional cents when dividing payments?

When splitting a value (like dividing 10 cents three ways), standard accounting practice dictates allocating the base divided amount to all parties, then distributing the remainder penny by penny until the remainder is zero. This ensures no money is ever created or destroyed by rounding.