Menu

Why invoice amounts should be stored as integer cents (PHP example)
📰

Why invoice amounts should be stored as integer cents (PHP example)

DEV Community: mysql·Murabyte·3 days ago
#ujOAAV98
#devtomysql#devto#dev#mysql#invoicing
Long article (423 words) — no AI summary yet.
Reading 0:00
15s threshold

Disclosure: I make WaInvoice at Murabyte, which is mentioned at the end.

Open a JavaScript or PHP console and add 0.1 and 0.2. You do not get 0.3 exactly. In an invoice, that kind of drift shows up as a total that is one cent off. The usual fix is to store money as whole cents.

The problem

$total = 0.1 + 0.2 ; var_dump ( $total == 0.3 ) ; // bool(false)

Enter fullscreen mode

Exit fullscreen mode

Binary floating point cannot store most decimal fractions exactly. With many line items, tax and discounts, rounding errors add up.

Store integer cents

function toCents ( string $s ) : int { if ( ! preg_match ( '/^\d+(\.\d{1,2})?$/' , $s ) ) { throw new InvalidArgumentException ( 'Invalid amount' ) ; } return ( int ) round ( ( ( float ) $s ) * 100 ) ; }

$unit = toCents ( '19.99' ) ; // 1999 $qty = 3 ; $line = $unit * $qty ; // 5997

Enter fullscreen mode

Exit fullscreen mode

Use an integer column in the database (BIGINT) for the amounts.…

Continue reading — create a free account

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