Principle:ClickHouse ClickHouse Decimal Arithmetic
| Knowledge Sources | |
|---|---|
| Domains | Numeric_Types, Data_Types |
| Last Updated | 2026-02-08 00:00 GMT |
Overview
A numerical representation system that provides exact decimal arithmetic by using scaled integers instead of binary floating-point.
Description
Decimal Arithmetic addresses the fundamental limitation of binary floating-point representation: many decimal fractions cannot be represented exactly in binary (e.g., 0.1 in decimal is a repeating fraction in binary). This leads to rounding errors that accumulate over repeated operations, which is unacceptable for financial calculations and other domains requiring exact decimal arithmetic.
The principle works by:
- Storing values as integers multiplied by a power of 10
- Maintaining a scale (number of decimal places) separately
- Performing all arithmetic on the integer representation
- Ensuring results are always exact within the precision limits
For example, $12.34 with scale=2 is stored as integer 1234. Operations like addition simply add the integers (assuming same scale), while multiplication requires scale adjustment.
Usage
Use this principle when:
- Implementing financial calculations (money, interest rates)
- Storing and computing with exact decimal values
- Avoiding accumulation of floating-point rounding errors
- Complying with regulations requiring exact decimal arithmetic
- Implementing database decimal types
Theoretical Basis
The principle is based on fundamental numerical analysis concepts:
Fixed-Point Arithmetic: Decimal types are a form of fixed-point arithmetic where the decimal point position (scale) is fixed and known. This contrasts with floating-point where the point "floats" based on the exponent.
Representation Invariant: For a decimal value `d` with scale `s`, the actual value is `d.value / 10^s`. Operations must preserve this invariant.
Precision vs. Range: Decimal types trade range for precision:
- `Decimal32`: 7 decimal digits
- `Decimal64`: 18 decimal digits
- `Decimal128`: 38 decimal digits
- `Decimal256`: 76 decimal digits
Arithmetic Complexity:
- Addition/Subtraction: Requires same scale, O(1) integer operation
- Multiplication: Result scale = sum of operand scales, may need scaling
- Division: Result scale determined by desired precision, requires wider intermediate