Menu

The one-cent bug: Math.floor(price * 100)
📰

The one-cent bug: Math.floor(price * 100)

DEV Community: javascript·Payneteasy·4 days ago
#vAqK9bpX
#devtojavascript#devto#dev#order#total
Reading 0:00
15s threshold

A merchant's finance team asked why a few orders a week were charged one cent less than the cart total.

The checkout built the gateway amount with Math.floor(price * 100) . For 19.99 that breaks: 19.99 * 100 is 1998.9999999999998 in IEEE 754, so floor returns 1998. The customer pays 19.98. Nobody complains about a missing cent, so it lived for months.

Our order total was stored as a decimal string, so the order said 19.99 and the gateway said 19.98. Reconciliation by order id flagged it, and someone had been closing those by hand as "rounding".

Fixes:

Never multiply a price by 100. Keep minor units as integers from the start (1999) and format for display only at the edge.

If you must parse a decimal string, split on the dot or use a decimal library, not floats.

We also added a guard before every charge call: the request amount must equal the integer total on the order, otherwise throw.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.