Decimal
Represents a mathematical decimal number (ℚ∩ℝ_decimal), with exact arithmetic operations that don't overflow and consistent behavior across all platforms.
Decimal vs Double/Float
Decimal vs Double/Float
The Decimal type is designed to replace floating-point types (Double and Float) where correctness matters. Floating-point binary representation cannot exactly represent most base-10 decimal values, leading to subtle rounding errors.
The Decimal type stores values as an exact scaled integer, avoiding all floating-point imprecision.
Why no division?
Why no division?
The set of terminating decimal numbers is not closed under division: dividing two terminating decimals can produce a non-terminating result (e.g., 1 / 3 = 0.333...). Division is therefore intentionally excluded from this type.
This is consistent with how Integer excludes operations that would leave the set of integers (square roots, noninteger divisions without remainder).
Key features
Key features
Creations: Create from Kotlin integer types, Integer, or decimal string (see fromLong, fromInteger, and parse).
Comparisons: Compare decimals using structural equality (
x == y,x != y) and ordering operators (x < y,x <= y,x > y,x >= y).Arithmetic operations: Add (
x + y), subtract (x - y), multiply (x * y), and negate (-x) decimals without overflow.Conversions: Convert to its canonical decimal string representation (see Decimal.toString).
Since
5.2.0