How Precision Works
- The default precision is 28 significant digits, matching Python’s
decimalmodule. - Operators
+-*+=-=*=(and reflected__radd__/__rsub__/__rmul__) round their result HALF_EVEN to the default precision (28 significant digits), matching Pythondecimal.Decimaldefault-context arithmetic. - Methods
.add(other)/.subtract(other)/.multiply(other)(and the in-place variants.add_inplace(other)/.subtract_inplace(other)/.multiply_inplace(other)) take an optionalprecision: Int = 0argument. The defaultprecision=0returns the exact, unrounded result; passingprecision > 0rounds HALF_EVEN to that many significant digits. - Division and mathematical functions (
sqrt,ln,exp, etc.) accept an optionalprecisionparameter specifying the number of significant digits in the result.
var a = Decimal("999999999999999999999999999999") # 30 nines
var b = Decimal("1")
# Operators round to 28 digits (matches Python decimal default context)
print(a + b) # 1.000000000000000000000000000E+30
# Methods at precision=0 (default) are exact
print(a.add(b)) # 1000000000000000000000000000000
# Methods accept an explicit precision
print(a.add(b, 50)) # 1000000000000000000000000000000 (exact, fits)
print(a.multiply(a, 40)) # 40-significant-digit rounded product
var x = Decimal("2")
print(x.sqrt()) # 28 significant digits (default)
print(x.sqrt(precision=100)) # 100 significant digits
print(x.sqrt(precision=1000)) # 1000 significant digits
Note
The default precision of 28 will be configurable globally in a future version when Mojo supports global variables.