Message 78671 - Python tracker (original) (raw)
FYI, there is already a lossless implementation in the docs:
def float_to_decimal(f): "Convert a floating point number to a Decimal with no loss of information" n, d = f.as_integer_ratio() with localcontext() as ctx: ctx.traps[Inexact] = True while True: try: return Decimal(n) / Decimal(d) except Inexact: ctx.prec += 1