Fairy
Resources

How to Avoid: Floating Point Used for Money

July 17, 2026 · 7-minute read · Fairy

The short answer

To prevent floating point used for money in AI-generated code, always represent currency as integer cents (or the smallest currency unit) rather than float dollars. Check all arithmetic operations—addition, multiplication, division—to ensure they operate on integers. AI models frequently generate float-based money code because training data contains this anti-pattern; explicit prompting and automated review catch it before production.

Why Floating Point Money Is a Critical AI Code Bug

To prevent floating point used for money in AI-generated code, represent all currency values as integers in the smallest unit (cents for USD, pence for GBP) rather than floating point dollars. This single change eliminates rounding drift that compounds across transactions and causes financial discrepancies.

AI code generators produce float-based money code frequently because this anti-pattern saturates their training data. Tutorials, Stack Overflow answers, and legacy codebases all demonstrate price = 19.99 rather than priceInCents = 1999. The model reproduces what it learned without understanding the downstream consequences.

This isn't a theoretical concern. Currency as floats causes rounding drift that accumulates over arithmetic operations—each calculation introduces tiny errors that compound into real money discrepancies in production systems.

How Floating Point Arithmetic Fails for Money

IEEE 754 floating point cannot represent most decimal fractions exactly. The number 0.1 in binary floating point is actually 0.1000000000000000055511151231257827021181583404541015625. This matters for money because:

// Looks correct, isn't correct
const price = 19.99;
const quantity = 3;
const total = price * quantity;
console.log(total); // 59.96999999999999, not 59.97

A single calculation might round correctly. But financial systems perform thousands of operations:

// Simulating many small transactions
let balance = 0.0;
for (let i = 0; i < 1000; i++) {
  balance += 0.01;
}
console.log(balance); // 9.999999999999831, not 10.00

The drift is small per transaction but significant at scale. An e-commerce platform processing thousands of orders daily will accumulate errors that show up in reconciliation, tax calculations, and customer disputes.

Why AI Models Generate This Bug

AI code generators learn patterns from training data. The floating point money anti-pattern appears everywhere:

When you prompt an AI to "create a shopping cart," it generates what it's seen most often:

// AI-generated code (problematic)
function calculateTotal(items) {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}

function applyDiscount(total, discountPercent) {
  return total * (1 - discountPercent / 100);
}

This code looks clean. It runs without errors. It passes basic tests. And it silently corrupts financial data in production.

The Correct Pattern: Integer Cents

Store and compute money as integers representing the smallest currency unit:

// Correct pattern: integer cents
function calculateTotalCents(items) {
  return items.reduce((sum, item) => sum + item.priceInCents * item.quantity, 0);
}

function applyDiscountCents(totalCents, discountPercent) {
  // Round explicitly when division is required
  return Math.round(totalCents * (1 - discountPercent / 100));
}

function formatCurrency(cents) {
  return `$${(cents / 100).toFixed(2)}`;
}

Key principles:

  1. Input boundaries: Convert to cents immediately when receiving money values
  2. Internal arithmetic: All calculations use integers
  3. Output boundaries: Convert to display format only at the final step
  4. Explicit rounding: When division is unavoidable, round explicitly with a documented strategy

Database Schema

-- Wrong: floating point
CREATE TABLE products (
  id SERIAL PRIMARY KEY,
  price DECIMAL(10, 2)  -- Still problematic in some languages
);

-- Correct: integer cents
CREATE TABLE products (
  id SERIAL PRIMARY KEY,
  price_cents INTEGER NOT NULL
);

API Contracts

// Wrong: float dollars
{
  "price": 19.99,
  "total": 59.97
}

// Correct: integer cents
{
  "price_cents": 1999,
  "total_cents": 5997
}

How to Detect Floating Point Money in AI Code

Check money is integer cents, not float dollars, through all arithmetic. Look for these signals in AI-generated code:

Red Flag Variables

// Suspicious variable names with float values
const price = 19.99;        // Should be priceInCents = 1999
const amount = 100.50;      // Should be amountInCents = 10050
const currency = 49.99;     // Should be currencyInCents = 4999

toFixed() as a Bandage

// toFixed hides the problem, doesn't fix it
const total = (price * quantity).toFixed(2);

toFixed() rounds the display output but doesn't fix intermediate calculations. The arithmetic still uses floats internally, accumulating errors before the final rounding.

Float Arithmetic on Money Fields

// Any arithmetic on float money values
total = subtotal + shipping + tax;
discount = price * 0.15;
perItem = total / quantity;

Database Queries Returning Floats

// ORM returning float prices
const product = await db.product.findUnique({ where: { id } });
const total = product.price * quantity; // price is float from DB

Automated Detection Strategies

Manual review catches obvious cases, but systematic detection requires automation:

Static Analysis Rules

Configure linters to flag suspicious patterns:

// ESLint custom rule concept
// Flag: variable named 'price', 'amount', 'cost', 'total' 
// assigned a float literal or used in float arithmetic

Code Review Checklists

When reviewing AI-generated code handling money:

  1. Trace money values from input to storage to output
  2. Verify all arithmetic operates on integers
  3. Check database schema uses INTEGER, not FLOAT/DOUBLE/DECIMAL
  4. Confirm API contracts specify cents, not dollars
  5. Look for toFixed() calls that indicate underlying float issues

Test Cases That Expose Drift

// Test that catches floating point drift
test('thousand small transactions should equal expected total', () => {
  let balance = 0;
  for (let i = 0; i < 1000; i++) {
    balance = addCents(balance, 1); // 1 cent each
  }
  expect(balance).toBe(1000); // Exactly 1000 cents
});

Handling Edge Cases

Division and Percentages

Division introduces fractions that require rounding decisions:

// Splitting a bill
function splitBillCents(totalCents, numberOfPeople) {
  const perPerson = Math.floor(totalCents / numberOfPeople);
  const remainder = totalCents % numberOfPeople;
  
  // First person pays the remainder (or distribute across first N)
  return Array.from({ length: numberOfPeople }, (_, i) => 
    perPerson + (i < remainder ? 1 : 0)
  );
}

// 1000 cents split 3 ways: [334, 333, 333] = 1000 ✓

Multi-Currency Systems

Different currencies have different smallest units:

const CURRENCY_UNITS = {
  USD: 100,  // cents
  JPY: 1,    // yen has no subunit
  KWD: 1000, // fils (3 decimal places)
};

function toSmallestUnit(amount, currency) {
  return Math.round(amount * CURRENCY_UNITS[currency]);
}

Interest Calculations

Financial formulas often require high precision:

// For complex financial calculations, use a decimal library
import Decimal from 'decimal.js';

function calculateInterest(principalCents, annualRate, days) {
  const principal = new Decimal(principalCents);
  const dailyRate = new Decimal(annualRate).div(365);
  const interest = principal.mul(dailyRate).mul(days);
  return interest.round().toNumber();
}

Prompting AI to Generate Correct Code

Explicit instructions improve AI output:

Create a shopping cart module.
Requirements:
- All money values stored as integer cents
- Variable names should end in 'Cents' (e.g., priceCents, totalCents)
- Division operations must use explicit rounding (Math.round, Math.floor)
- Display formatting should only happen at output boundaries

Even with good prompts, AI may revert to float patterns in complex code. Verification remains essential.

The Broader Pattern: AI Logic Bugs

Floating point money is one instance of a broader category: logic bugs that pass syntax checks and basic tests but produce incorrect results in production. Related patterns include:

These bugs share a common trait: AI generates code that looks correct and runs without errors, but violates domain-specific invariants that weren't explicit in the prompt. Detecting them requires understanding what correct behavior means in context, not just whether the code executes.

Implementing Systematic Review

For teams deploying AI-generated code in production, systematic detection beats ad-hoc review:

  1. Define patterns: Document what floating point money bugs look like in your codebase
  2. Automate detection: Add linter rules, test cases, and review checklists
  3. Verify before merge: Every AI-generated PR touching money logic gets explicit review for this pattern
  4. Monitor production: Track reconciliation discrepancies that might indicate undetected drift

Tools like Fairy Scout can automate detection of logic bugs like floating point money in AI-generated pull requests, catching issues before they reach production.

Summary

Floating point used for money is a high-frequency AI code bug because the anti-pattern dominates training data. The fix is straightforward: represent currency as integer cents, perform all arithmetic on integers, and convert to display format only at output boundaries.

Detection requires checking that money is integer cents, not float dollars, through all arithmetic—from input boundaries through database storage to API responses. Automated review catches this pattern systematically, preventing rounding drift from reaching production systems where it compounds into real financial discrepancies.

For teams shipping AI-generated code, this is one of several logic bugs that require domain-aware verification. Fairy's code verification provides systematic detection of these patterns, ensuring AI-generated work meets production standards before deployment.

Frequently asked questions

Why does AI generate floating point code for money?

AI models learn from training data that includes widespread float-based money code. Since this anti-pattern appears frequently in tutorials and legacy codebases, models reproduce it without understanding the rounding consequences.

What problems does floating point money cause?

Floating point arithmetic introduces rounding drift that compounds over transactions. A $19.99 item might calculate as $19.989999999999998, and these small errors accumulate into significant discrepancies in financial reports and customer charges.

How do I convert existing float money code to integers?

Multiply dollar amounts by 100 at input boundaries, perform all arithmetic in cents, and divide by 100 only for display. Audit database schemas and API contracts to ensure the integer representation flows through the entire system.

Does toFixed() solve floating point money problems?

No. toFixed() rounds for display but doesn't fix the underlying arithmetic. Calculations still use floats internally, so rounding errors accumulate before toFixed() is applied. Use integer cents for all math, not display-level fixes.


Have AI-generated work you’d want verified? Connect with a Fairy → or run a free check with Scout.

More resources