Skip to content

Instantly share code, notes, and snippets.

@rvause
Created September 20, 2012 10:28
Show Gist options
  • Select an option

  • Save rvause/3755131 to your computer and use it in GitHub Desktop.

Select an option

Save rvause/3755131 to your computer and use it in GitHub Desktop.
Support for decimals where your target might be Python older than 2.7
import sys
from decimal import *
LT_27 = True if sys.version_info < (2, 7) else False
def f2d(f):
"""
Convert a floating point number to a Decimal with no loss of information
from http://docs.python.org/release/2.6.7/library/decimal.html#decimal-faq
"""
n, d = f.as_integer_ratio()
numerator, denominator = Decimal(n), Decimal(d)
ctx = Context(prec=60)
result = ctx.divide(numerator, denominator)
while ctx.flags[Inexact]:
ctx.flags[Inexact] = False
ctx.prec *= 2
result = ctx.divide(numerator, denominator)
return result
def d(f):
return f2d(f) if LT_27 else f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment