DEV Community

Payneteasy
Payneteasy

Posted on

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

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:

  1. Never multiply a price by 100. Keep minor units as integers from the start (1999) and format for display only at the edge.
  2. 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. It found two more places with the same math, a refund path and a tax line.

The error sits below everyone's notice threshold, so it survives.

Do you keep money as integers end to end, or is there still a float hiding in a refund or tax path?

Payneteasy handles this kind of payment flow for merchants and PSPs — see how it works.

Top comments (0)