Decimal In, Decimal Out (BigFloat)
Every binary float is exactly a decimal, because 2^-k is 5^k / 10^k, so
the conversion out loses nothing and only the number of digits is a choice:
var tenth = BigFloat.from_float64(0.1)
print(tenth.to_bigdecimal()) # all 55 digits of the double
print(tenth.to_bigdecimal_rounded(17)) # 0.10000000000000001
print(tenth) # as many digits as 53 bits are worth
print(tenth.internal_representation()) # the significand, exponent, precision
A digit count costs what the digits cost. The digits asked for are taken by
scaling the value by a power of ten, so a deep exponent is no longer a reason
to wait: a value whose exact expansion runs to 301,031 digits still gives
twenty of them at once, and the smallest and largest values a BigFloat can
hold print like any other.
var deep = BigFloat.power_of_two(-1000000)
print(deep.to_string(20)) # 1.0100340591980302247E-301030
to_bigdecimal() is the one to ask when every digit is wanted, and it is the
only one whose cost follows the exponent, because the answer does.
Coming in costs what the precision is, in the same way and for the same reason. A decimal exponent of nine or eighteen figures is a decimal nobody could write out, and it parses at once:
var deep = BigFloat.from_string("1.5e-1000000", 53)
print(deep.to_string(17)) # 1.5000000000000000E-1000000
print(BigFloat.from_string("7e1000000000", 53).to_string(17))
# 6.9999999999999999E+1000000000
The second one is seven to a billion powers of ten, which has no exact rendering in 53 bits – the digits shown are the float’s own.
Going the other way rounds. to_float64() is exact for a normal double but
rounds a second time when the answer is subnormal, since a subnormal has fewer
bits than 53: converting from a wider precision avoids it.