Representing Decimal Amounts
Store currency amounts in a representation whose scale and rounding rules match the operations the application promises.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Preserve the decimal input
Three values written as "0.10" can be converted into integer cents and added to 30 cents. For currencies with multiple scales, record the currency and its unit. Python's parsing and formatting boundary separates those stored cents from a label displaying 0.30.
Specify when rounding occurs
Splitting one cent equally among three recipients cannot give three equal integer-cent payments that total one cent. Assign the leftover cent by a documented ordering rule. A function contract should state both the rounding unit and who receives any remainder.[1][2]
Choose whether the quantity is exact under decimal rules
A reservation costs 8.25 in a currency with one hundred minor units per major unit. Three such reservations total 2475 minor units, displayed as 24.75. You can store 825 and perform the multiplication on integers. A decimal arithmetic type is useful when rules also involve fractional minor units or decimal rates. Give the stored numbers a currency and a scale. Adding 825 minor units across two currencies without conversion produces a number with no single currency meaning. See values and units.
Allocate a remainder deliberately
Imagine splitting 10.00 into three equal payments. Dividing 1000 minor units by three yields 333 each and remainder one. Under one documented rule, the first recipient gets the extra unit and the amounts are 3.34, 3.33, and 3.33. Rounding each exact share independently to 3.33 gives 9.99 instead. A reproducible allocation should choose the tie order and test that allocations always sum to the original amount. The quotient and remainder give the exact arithmetic for both the base share and the leftover. When regulatory or contractual rounding rules exist, put their choice at the amount boundary.