How to represent currency or money in C

Never use floating point for storing currency. Floating point numbers cannot represent tenths or hundredths, only diadic rationals, i.e. numbers of the form p/q where p and q are integers and q is a power of 2. Thus, any attempt to represent cents others than 0, 25, 50, or 75 cents will require an approximation, and these approximations translate into vulnerabilities that can be exploited to make you lose money.

Instead, store integer values in cents (or whatever the smallest division of the currency is). When reading values formatted with a radix point, simply read the whole currency units and cents as separate fields, then multiply by 100 (or the appropriate power of 10) and add.

Leave a Comment