PHP

Money Is Not a Float: Decimals, Rounding and Cents in PHP, Python and JavaScript

I ran the same money math through PHP 8.6, Python 3.15 and Node 26. They round 2.675 differently, bcadd('0.1', '0.2') returns 0, PHP's BcMath\Number turns a float 0.1 into 0 with only a deprecation notice, and JSON.parse quietly changes 9007199254740993 to ...992.

Every developer learns that 0.1 + 0.2 isn't 0.3, nods, and goes back to storing prices in a float column. The famous example is harmless. The real damage comes from rounding rules that differ between languages, decimal libraries with surprising defaults, and JSON parsers that quietly change large numbers. Those are the bugs that show up as a one-cent mismatch in a reconciliation report three months after launch.

Money code lives in all three of these languages at once surprisingly often: a PHP storefront, a Python billing job and a Node checkout API, all reading the same tables. So I ran the same money operations through PHP 8.6.0 (with bcmath), Python 3.15.2 and Node 26.13.1, and compared what each one gives you.

Money Math in PHP, Python and JavaScript: The Short Version

Question PHP 8.6 Python 3.15 Node 26
0.1 + 0.2 0.30000000000000004 0.30000000000000004 0.30000000000000004
Add 0.10 a million times 100000.00000133288 100000.00000133288 100000.00000133288
Round 2.675 to 2 places round(): 2.68 round(): 2.67 toFixed(2): "2.67"; Math.round(x*100)/100: 2.68
Round 2.5 / −2.5 3 / −3 (half away from zero) 2 / −2 (half to even) 3 / −2 (half toward +∞)
Built-in decimal type bcmath strings, BcMath\Number (8.4+) decimal.Decimal none
Integers past 2^53 exact (64-bit ints) exact (unbounded ints) only with BigInt

The floating-point results are identical, because all three use IEEE 754 doubles. Everything else differs, so one price can round three different ways depending on which service handles it.

Rounding: Same Number, Three Answers

PHP 8.6.0
0.1 + 0.2                                0.30000000000000004
0.1 + 0.2 == 0.3                         false
sum of 0.10 a million times              100000.00000133288
round(2.675, 2)                          2.68
round(2.5) / round(-2.5)                 [3,-3]
round(2.5, 0, PHP_ROUND_HALF_EVEN)       2.0
Python 3.15.2
0.1 + 0.2                                0.30000000000000004
0.1 + 0.2 == 0.3                         False
sum of 0.10 a million times              100000.00000133288
round(2.675, 2)                          2.67
round(2.5), round(-2.5)                  (2, -2)
Node v26.13.1
0.1 + 0.2                                0.30000000000000004
0.1 + 0.2 === 0.3                        false
sum of 0.10 a million times              100000.00000133288
Math.round(2.675 * 100) / 100            2.68
(2.675).toFixed(2)                       "2.67"
Math.round(2.5), Math.round(-2.5)        "3, -2"
(1.005).toFixed(2)                       "1.00"

The value 2.675 can't be stored exactly as a double. It's really 2.67499999999999982236431605997495353221893310546875, so a correct round-half-up gives 2.67. Python's round() and JS's toFixed() do exactly that. PHP's round() gives 2.68, because it deliberately compensates for that representation error to return what you'd expect from the decimal you typed. JS's Math.round(2.675 * 100) / 100 also lands on 2.68, by accident: 2.675 * 100 happens to come out as exactly 267.5, while 1.005 * 100 comes out as 100.49999999999999, so the same idiom rounds 1.005 down. It's right for some inputs and wrong for others. (1.005).toFixed(2) gives "1.00".

The tie rules differ too. Python's round() uses banker's rounding (half to even), so round(2.5) is 2. PHP rounds half away from zero, so 3 and −3, unless you pass PHP_ROUND_HALF_EVEN. JS's Math.round rounds half toward positive infinity, so Math.round(-2.5) is −2. That's three behaviors for the same input, and none of them is wrong. They're just different.

The fix isn't to pick the "right" float rounding. Don't round floats at all for money.

We recommend reading RSA in Python From Scratch: The Math, the Code, and What Breaks It to continue reading our selection of content. Arbitrary-precision integers are what make Python's money math easy, and this RSA build shows how far they go.

RSA in Python From Scratch: The Math, the Code, and What Breaks It Build RSA in Python from first principles — Extended Euclidean Algorithm, modular exponentiation and key generation, with every output executed. SudoSecurity · Santhdium

The Decimal Types and Their Traps

PHP's bcmath works on numeric strings with an explicit scale, the number of digits after the point. The default scale is 0:

bcadd('0.1', '0.2')   (default scale)    0
bcadd('0.1', '0.2', 2)                   0.30
bcdiv('2', '3', 2)   (truncates)         0.66
bcround('0.666', 2)                      0.67

bcadd('0.1', '0.2') returns 0. Not 0.3. It truncates to the default scale without a warning. bcdiv truncates too, so 2 ÷ 3 at scale 2 gives 0.66, not 0.67. PHP 8.4 added bcround(), which finally lets you round properly, and the BcMath\Number class:

new Number('0.1') + new Number('0.2')    0.3
Number('19.99') * 3                      59.97
Number('100') / 3                        33.3333333333
(Number('100') / 3)->round(2)            33.33

Deprecated: Implicit conversion from float 0.1 to int loses precision in /w/money.php on line 23
new Number(0.1)  (float in)              0

BcMath\Number tracks scale for you, supports normal operators (+, *, /), and has a round() method. It's the API PHP should have had all along. But look at the last line. new Number(0.1) returned 0, with only a deprecation notice. The constructor accepts int|string, so a float gets coerced to an int. In production, with deprecation notices turned off, that's a price silently becoming zero. Always build a Number from a string.

Python's Decimal has the opposite trap:

Decimal('0.1') + Decimal('0.2')          Decimal('0.3')
Decimal(0.1)  (float in)                 Decimal('0.1000000000000000055511151231257827021181583404541015625')
Decimal('2.675').quantize(HALF_UP)       Decimal('2.68')
Decimal('2.665').quantize(default)       Decimal('2.66')
getcontext().rounding                    'ROUND_HALF_EVEN'
Decimal('100') / 3                       Decimal('33.33333333333333333333333333')
math.fsum vs sum([0.1]*10)               (1.0, 1.0)

Decimal(0.1) doesn't give you 0.1. It gives you the exact binary value of the float, all 55 digits of it. Build Decimals from strings, never from floats. The default rounding mode is ROUND_HALF_EVEN, so Decimal('2.665').quantize(Decimal('0.01')) gives 2.66. If your finance team expects half-up, pass rounding=ROUND_HALF_UP every time, or set it on the context.

The math.fsum vs sum line shows something newer: sum([0.1] * 10) gives exactly 1.0. Since Python 3.12, the built-in sum() uses compensated summation for floats. That's nice, but it doesn't help the += loop, which still drifts. Don't count on it to rescue float money.

JavaScript has no decimal type. The TC39 Decimal proposal hasn't shipped, so your options are integer cents in a Number (exact up to Number.MAX_SAFE_INTEGER, 9,007,199,254,740,991), BigInt cents, or a library.

Integer Cents: The Boring Answer That Works

Storing money as an integer count of the smallest unit (cents) works identically in all three languages, because integer arithmetic is exact. The problems move to the edges: division and splitting.

def allocate(total_cents: int, ratios: list[int]) -> list[int]:
    """Split an amount in integer cents by ratios; leftover cents go to the first shares."""
    total_ratio = sum(ratios)
    shares = [total_cents * r // total_ratio for r in ratios]
    for i in range(total_cents - sum(shares)):
        shares[i] += 1
    return shares

print(allocate(10000, [1, 1, 1]))        # $100 three ways
print(allocate(500, [70, 20, 10]))       # $5.00 by 70/20/10
print(round(100 / 3, 2) * 3)             # the float way: shares that don't add back up
[3334, 3333, 3333]
[350, 100, 50]
99.99

$100 split three ways can't be three equal cent amounts. The allocator gives 33.34 + 33.33 + 33.33 = 100.00, and the extra cent goes somewhere deliberate. The float version rounds each share to 33.33 and loses a cent: 99.99. Every payment splitter, refund calculator and tax distribution needs an allocator like this. You can't avoid the remainder. You can only decide where it goes.

Two more rules for cents:

  • Not every currency has 2 decimals. JPY has 0, and BHD and KWD have 3. Store the currency code next to the amount and look up the exponent (ISO 4217) instead of hardcoding 100.
  • Format with Intl.NumberFormat or your locale library, not string concatenation. The Node run:
Intl.NumberFormat en-US USD              "$1,234.50"
Intl.NumberFormat de-DE EUR              "1.234,50\u00a0€"
Intl.NumberFormat ja-JP JPY              "¥1,235"

That's the same number, 1234.5, rendered three ways. The \u00a0 is a no-break space, which Intl puts before the euro sign, so don't compare formatted strings against hand-typed ones. Yen has no minor unit, so Intl rounds it to ¥1,235. Formatting is for display only. Keep the stored value in integer minor units.

JSON: Where Precision Goes to Die

Money crosses service boundaries as JSON, and JSON numbers have no defined precision:

JSON.parse('9007199254740993')           9007199254740992
JSON.parse with source (reviver)         9007199254740993

JSON.parse("9007199254740993") gives 9007199254740992, off by one with no error. Any ID or amount in minor units above 2^53 that passes through a JS service is at risk. Node 26 supports the newer reviver context.source (the second line), which gives you the original text so you can convert it to BigInt, but only if you remember to use it.

PHP and Python handle the same input differently:

json_encode(0.1 + 0.2)                   0.30000000000000004
json_decode('9007199254740993')          9007199254740993
json_decode('12345678901234567890')      1.2345678901234567E+19
...with JSON_BIGINT_AS_STRING            12345678901234567890
json.dumps(Decimal)                      'TypeError: Object of type Decimal is not JSON serializable'
json.loads('0.1', parse_float=Decimal)   Decimal('0.1')
json.loads('12345678901234567890')       12345678901234567890

PHP parses 9007199254740993 exactly, since its 64-bit integers go up to about 9.2 × 10^18, but a 20-digit number becomes a float (1.2345678901234567E+19) unless you pass JSON_BIGINT_AS_STRING. Python parses big integers exactly every time, and with parse_float=Decimal keeps decimals exact too. But json.dumps refuses Decimal outright with a TypeError. That's the honest behavior, and it means you need a custom encoder.

The interop rule: send money as a string or as integer minor units, never as a JSON float. {"amount": "19.99", "currency": "USD"} or {"amount_minor": 1999, "currency": "USD"}.

PHP's Float Output Hides the Drift

One more PHP-specific trap. Here's the same float sum printed three ways:

echo / string cast:  499879651.03
var_export:          499879651.0299984
json_encode:         499879651.0299984
ini precision=14 serialize_precision=-1

echo and string conversion use precision=14, so they show a clean 499879651.03. The actual value is 499879651.0299984, which is what var_export and json_encode (using serialize_precision=-1) show. Your logs and templates show the tidy version, while the API sends the real one. If a PHP report and a JSON consumer disagree by a fraction of a cent, this is the first place to look.

The Database Can Undo All of It

Picking the right type in code doesn't help if the column throws it away. SQLite, which is what most tutorials, test suites and small apps start on, lets you write DECIMAL(10,2) and accepts it without complaint. Then this happens:

import sqlite3
from decimal import Decimal

db = sqlite3.connect(":memory:")
print("SQLite", sqlite3.sqlite_version)
db.execute("CREATE TABLE orders (price DECIMAL(10,2), price_cents INTEGER)")
try:
    db.execute("INSERT INTO orders VALUES (?, ?)", (Decimal("19.99"), 1999))
except sqlite3.ProgrammingError as e:
    print("insert Decimal:", e)
db.executemany("INSERT INTO orders VALUES (?, ?)", [("0.10", 10)] * 1000)   # strings, the 'safe' way
row = db.execute("SELECT typeof(price), price FROM orders LIMIT 1").fetchone()
print("stored as:", row)
print("SUM(price):      ", db.execute("SELECT SUM(price) FROM orders").fetchone()[0])
print("SUM(price_cents):", db.execute("SELECT SUM(price_cents) FROM orders").fetchone()[0])
print("SUM(price) = 100:", db.execute("SELECT SUM(price) = 100 FROM orders").fetchone()[0])
db.execute("CREATE TABLE cart (price DECIMAL(10,2))")
db.executemany("INSERT INTO cart VALUES (?)", [("0.10",), ("0.20",)])
print("cart SUM(price):        ", db.execute("SELECT SUM(price) FROM cart").fetchone()[0])
print("cart SUM(price) = 0.30: ", db.execute("SELECT SUM(price) = 0.30 FROM cart").fetchone()[0])
print("'19.99' * 3:            ", db.execute("SELECT CAST('19.99' AS DECIMAL(10,2)) * 3").fetchone()[0])
SQLite 3.53.1
insert Decimal: Error binding parameter 1: type 'decimal.Decimal' is not supported
stored as: ('real', 0.1)
SUM(price):       100.0
SUM(price_cents): 10000
SUM(price) = 100: 1
cart SUM(price):         0.30000000000000004
cart SUM(price) = 0.30:  0
'19.99' * 3:             59.97

Three things worth knowing:

  • DECIMAL(10,2) is stored as a float. typeof(price) says real. SQLite gives a DECIMAL column NUMERIC affinity, and its docs say text that's "a well-formed integer or real literal" gets converted to INTEGER or REAL. Inserting the string '0.10', which feels like the safe way, still produced a float.
  • Python won't bind a Decimal at all. sqlite3 raised type 'decimal.Decimal' is not supported. That error is the honest outcome. The quiet failure is the developer who converts with float() to make it go away.
  • The drift is back. Two cart rows of 0.10 and 0.20 summed to 0.30000000000000004, and SUM(price) = 0.30 was false. The 1,000-row sum came out as exactly 100.0, because newer SQLite versions sum floats with an error-compensating algorithm, but that's luck in the aggregate, not exact storage. The integer price_cents column summed to 10000 exactly, every time.

Postgres NUMERIC and MySQL DECIMAL are true decimal types, so this is a SQLite-specific trap. But SQLite is where a lot of code gets written and tested before it moves to a server database, and a test suite on SQLite can pass with money math that only breaks in production, or the other way around. Integer cents behave identically on every engine.

We recommend reading RSA in JavaScript: Your Numbers Are Too Small to continue reading our selection of content. BigInt is the same tool for cents and for crypto, and this shows where Number arithmetic falls apart.

RSA in JavaScript: Your Numbers Are Too Small Implement RSA in JavaScript with BigInt. Why Number arithmetic silently corrupts RSA at 26 bits, and what Web Crypto does instead. SudoSecurity · Santhdium

What Exactness Costs

Summing a million prices (each language uses its own random data, so compare within a row group, not across). Every timing is a second run after a warm-up:

PHP 8.6.0, 1,000,000 prices
float +=                          9.4 ms  499879651.03
int cents +=                      8.0 ms  49987965103
bcadd(..., 2)                   142.2 ms  499879651.03
BcMath\Number +                 184.4 ms  499879651.03
Python 3.15.2 , 1,000,000 prices
float += (loop)                  12.0 ms  499921531.5300302
sum(floats)                       3.6 ms  499921531.53
sum(int cents)                    5.8 ms  49992153153
sum(Decimals)                    34.9 ms  499921531.53
Decimal(str) + sum              107.4 ms  499921531.53
Node v26.13.1 , 1,000,000 prices
float +=                         20.8 ms  495233047.37003607
int cents +=                     13.7 ms  49523304737
BigInt cents +=                  14.1 ms  49523304737
Float Integer cents Decimal
PHP 8.6 9.4 ms 8.0 ms 142.2 ms (bcadd), 184.4 ms (Number)
Python 3.15 12.0 ms (loop), 3.6 ms (sum) 5.8 ms 34.9 ms (sum of Decimals), 107.4 ms including parsing
Node 26 20.8 ms 13.7 ms 14.1 ms (BigInt cents)

Integer cents cost the same as floats or less, everywhere. Decimal types cost 4–20x more. That's irrelevant for a checkout, and it matters for a batch job over a few hundred million ledger rows. The float sums also show the drift: Python's loop ended at ...531.5300302 and Node's at ...047.37003607. That's real error in the last digits, while every integer and decimal sum was exact.

What This Doesn't Cover

  • Server database drivers. What each Postgres and MySQL driver hands back for NUMERIC (string, float or decimal) varies by language and library, and that deserves its own test.
  • Currency conversion. Exchange rates need more precision than the currencies themselves, and the rounding point is a business decision.
  • Tax rules. Line-level vs invoice-level rounding is set by law in many places, not by code style.
  • Money libraries. brick/money (PHP), py-moneyed and dinero.js wrap all of this. Use one once you understand what it does.

The Actual Point

Floats are identical across PHP, Python and JavaScript, and wrong identically. Everything built on top is different: three tie-breaking rules, a bcmath default scale that truncates to zero, a PHP Number constructor that turns a float into 0, a Python Decimal constructor that keeps every float artifact, and a JS JSON parser that changes big numbers without telling you. Store integer minor units with a currency code, do decimal math from strings when you need fractions, put an allocator in front of every split, send money over JSON as strings or integers, and pick one rounding mode for the business and write it down.

Sources: php.net's bcmath and BcMath\Number documentation, the Python decimal and json documentation, and MDN and ECMAScript references for Number, BigInt, JSON.parse and Intl.NumberFormat. All results were run by me on php:8.6-cli rebuilt with bcmath, intl and mbstring, Python 3.15.2 and node:26-slim. Every script and output block above is reproduced verbatim from those runs; the scripts are original code using each language's documented API.

$ tail -f /forums

Discussion

Comments live on the community forums — sign in there to reply.