Decimal-scaled integers in C
Represent prices as integer cents and reject sums that exceed the integer range.
Choose the unit before choosing the type
In fixed-point arithmetic, each stored integer counts a fixed unit. With a scale
divisor of 100, each step is one cent. Every value using the type shares that scale. A C
int64_t holds the integer, and the program supplies its meaning.
A charge of $19.99 is 1999 cents and a $2.50 credit is -250 cents.
Since the scales match, adding the raw counts gives 1749, or $17.49.
Values with fractions of a cent need a rounding rule. For example, a $1.00 charge split among
three people leaves one cent after assigning 33 cents each. The application decides who gets it.
When the input is decimal text, read it into cents directly. For example, split
"19.99" into 19 whole dollars and 99 cents. Multiplying a binary double
by 100 and casting to an integer can discard a cent. On the course target, the binary64 product
0.29 * 100 is about 28.999999999999996, which truncates to 28.
The scale belongs to the field
A cent is a minor unit of the US dollar. Stripe takes USD amounts in cents,
so 1099 means $10.99. Its Japanese yen amounts use whole yen.
Keep the currency alongside the count so the program can apply the right scale.
Stripe amount units
Microsoft BASIC PDS 7 for DOS offered a CURRENCY type with four decimal places
alongside its floating-point types.
Microsoft BASIC numeric formats
A fixed-scale value can use different encodings. The packed-decimal field 12 34 5D
with two fractional digits decodes to the integer -12345 cents. The program can do
arithmetic on that integer and pack it again when writing the record.
COBOL packed-decimal example
Check the range before adding
C signed overflow has undefined behavior. For a positive right operand, the largest safe
left operand is INT64_MAX - rhs. For a negative right operand, the smallest safe left
operand is INT64_MIN - rhs. Each bound calculation fits because you select it
using the sign of rhs.
Return a success flag and write the sum only when it fits. That gives the caller a way to reject the transaction and keep its previous balance.
C11 draft §§6.3.1.4 and 6.5, integer conversions and representability
Exercises
1. Price and split
Start with $12.75, add a $3.50 charge and subtract a $1.20 credit. Write the balance in cents. Then divide the balance evenly among four people. How many cents remain after giving each person the same whole-cent amount?
Check the result
1275 + 350 − 120 = 1505 cents. Give each person 376 cents and allocate the
remaining cent according to your application's rule.
2. Implement checked addition
Write bool cents_add(int64_t lhs, int64_t rhs, int64_t *result) from scratch.
The inputs are counts of cents and a valid output pointer. Return true and write
the sum when it fits. On overflow, return false and leave the pointed-to value alone.
Try 1999 + (-250), then the pairs (INT64_MAX, 1) and
(INT64_MIN, -1). Before each overflow test, set the output to a known value and
check that it stays there.
Compare with a runnable solution
Save the code as cents.c.
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
/* Add two cent amounts. The caller supplies a valid result pointer.
* Return false on overflow and leave the result unchanged.
*/
bool cents_add(int64_t lhs, int64_t rhs, int64_t *result)
{
if (rhs > 0 && lhs > INT64_MAX - rhs) {
return false;
}
if (rhs < 0 && lhs < INT64_MIN - rhs) {
return false;
}
*result = lhs + rhs;
return true;
}
int main(void)
{
int64_t total;
if (!cents_add(1999, -250, &total)) {
return 1;
}
printf("%" PRId64 "\n", total);
if (cents_add(INT64_MAX, 1, &total) || total != 1749) {
return 1;
}
if (cents_add(INT64_MIN, -1, &total) || total != 1749) {
return 1;
}
return 0;
}
cc -std=c11 -Wall -Wextra -pedantic cents.c -o cents
./cents
1749