Integers, money and rounding in C++
Choose integer types, avoid overflow, store money in cents, round integer division the way the business wants, know when floating point is fine, and compute percentiles.
Business rules are full of numbers: prices, minutes, limits, rates. Getting them exactly right is mostly about choosing the right type and rounding at the right moment.
Pick the integer type
intis at least 32 bits: fine for counts and small values.std::int64_t(from<cstdint>) for money, timestamps, and anything that adds up over time.std::uint64_tfor hashes and bit patterns, where wrap-around is intended.std::size_tfor sizes and indices of containers.
Mixing signed and unsigned is a classic trap: if (index - 1 >= 0) is always true when index is
unsigned, because 0u - 1 is a huge positive number. Turn on -Wall -Wextra -Wsign-compare.
Overflow
Signed overflow is undefined behaviour: the compiler may assume it never happens. If a value can grow, make the type big enough, or check before you multiply:
if (rate != 0 && elapsed > std::numeric_limits<std::int64_t>::max() / rate) {
/* cap it instead of overflowing */
}Rate limiters hit this when a bucket has been idle for weeks: elapsed * rate gets enormous, so
cap the result at the bucket's capacity before anything can overflow.
Money in whole cents
Floating point can't represent 0.10 exactly. Represent money as an integer number of cents,
and convert only at the edges:
using Cents = std::int64_t;
std::string format(Cents c) {
const Cents abs = c < 0 ? -c : c;
const Cents cents = abs % 100;
return (c < 0 ? "-" : "") + std::to_string(abs / 100) + (cents < 10 ? ".0" : ".") +
std::to_string(cents);
}Parse "12.5" and "12.50" without ever going through double: split at the dot and read both
parts as integers. Build it in invoice totals for Ledgerly.
Rounding integer division
Integer division in C++ truncates toward zero: 7 / 2 == 3, -7 / 2 == -3. Business rules
usually want something else:
// For a >= 0 and b > 0:
std::int64_t ceil_div(std::int64_t a, std::int64_t b) { return (a + b - 1) / b; } // started hours
std::int64_t round_half_up(std::int64_t a, std::int64_t b) { return (a + b / 2) / b; }"Every started hour is charged" is ceil_div(minutes, 60). VAT of 19% on 1,999 cents is
round_half_up(1999 * 19, 100). Write down when you round (per line or once per total) as
carefully as how; tickets that say "round once per rate" mean that the sum is rounded, not
each line. For negative amounts, decide the rule (half away from zero?) and test it explicitly.
Floating point: when it's fine and when it isn't
double is fine for measurements: temperatures, averages, percentages for display. It isn't fine
for equality checks or money:
0.1 + 0.2 == 0.3 // false
std::abs(a - b) < 1e-9 // compare with a tolerance insteadIn tests, use doctest::Approx (see unit testing). When printing,
round once at the end: out << std::fixed << std::setprecision(1) << value (from <iomanip>).
Averages, medians and percentiles
- Average: sum in a wide type, then divide. Decide what an empty list returns.
- Median and percentiles: sort the values first.
- Nearest-rank percentile: the p-th percentile of n sorted values is the value at rank
ceil(p / 100 * n), counting from 1. Do that in integers:rank = ceil_div(p * n, 100), then indexrank - 1, with rank at least 1.
Other definitions interpolate between values, so match the one the ticket asks for. See log analysis for Tracehound.
Number bases
Turning a number into base 62 is repeated division; reading it back is repeated multiplication:
constexpr std::string_view digits =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string encode(std::uint64_t n) {
if (n == 0) return "0";
std::string out;
while (n > 0) { out += digits[n % 62]; n /= 62; }
std::ranges::reverse(out);
return out;
}When decoding, reject unknown characters and check for overflow before value * 62 + digit.
That's the core of the link shortener for Hopwire.
Questions and answers
- Why shouldn't I store money in a double?
- Most decimal amounts, like 0.10, have no exact binary representation, so sums drift by fractions of a cent and comparisons fail. Store whole cents in a 64-bit integer and convert only when parsing and printing.
- How do I round up an integer division in C++?
- For non-negative a and positive b: (a + b - 1) / b. Integer division in C++ truncates toward zero, so for negative values work out the rule separately and test it.
Practise it in a project
These projects put this guide to work, with tickets, tests and code review.
Ledgerly
Invoice totals for Ledgerly
Read amounts, compute net, VAT and gross totals to the cent, and never lose a cent to floating point.
- integer arithmetic
- rounding
- parsing
- exceptions
ParkPoint
Parking fees for ParkPoint
Compute what ParkPoint's pay machines charge: stays across midnight, a free grace period, a daily cap and an evening flat rate.
- time arithmetic
- integer rounding
- business rules
- boundary testing
Gatekeep
Rate limiting for Gatekeep
Protect Gatekeep's customers from traffic floods with token buckets: exact integer refills, a testable clock, per-client limits and bounded memory.
- token buckets
- injected time
- integer arithmetic
- memory bounds
Hopwire
Link shortener for Hopwire
Build the core of Hopwire's link shortener: turn long campaign URLs into short codes and back again, then give the support team a console to use it.
- hash maps
- number bases
- input validation
- streams
- unit tests