Conversion and Output (Decimal)
String output
The to_string() method provides flexible formatting:
var x = Decimal("123456789.123456789")
print(x) # 123456789.123456789
print(x.to_string(scientific=True)) # 1.23456789123456789E+8
print(x.to_string(engineering=True, force_exponent=True)) # 123.456789123456789E+6
print(x.to_string(delimiter="_")) # 123_456_789.123_456_789
print(x.to_string(line_width=20)) # Multi-line output
print(x.to_string(force_plain=True)) # Suppress auto-scientific notation
Default output follows CPython’s Decimal.__str__() rules: plain notation when
feasible, scientific notation when there would be more than 6 leading zeros
or the exponent is positive.
Dec128 does not switch: it is bounded to 29 digits and a scale of 0 to 28,
so plain notation is never longer than 30 characters, and it always prints
plain (the .NET System.Decimal rule). The two types therefore print the
same value differently below 1E-6 and at a positive exponent:
print(Decimal("1E-7")) # 1E-7
print(Dec128("1E-7")) # 0.0000001
print(Decimal("1E+28")) # 1E+28
print(Dec128("1E+28")) # 10000000000000000000000000000
print(Decimal("1E-6"), Dec128("1E-6")) # 0.000001 0.000001
To get the other form: Decimal.to_string(force_plain=True) and
Dec128.to_string(scientific=True).
Convenience aliases:
x.to_scientific_string() # to_string(scientific=True)
x.to_eng_string() # to_string(engineering=True)
x.to_string_with_separators("_") # to_string(delimiter="_")
to_chinese() writes the number in Chinese numerals; see
Chinese Numerals for the reading rules and the available
styles.
print(Decimal("1050.07").to_chinese()) # 一千零五十点零七
repr()
print(repr(Decimal("123.45"))) # BigDecimal("123.45")
Decimal numeric conversions
var n = Int(Decimal("123.99").truncate()) # 123; Int() alone raises on a fraction
var f = Float64(Decimal("3.14")) # 3.14 (may lose precision)