In Python, there are classes in the standard library fractions.Fraction and decimal.Decimal that help you more accurately define arithmetic with rational numbers. For an unfamiliar example where it helps:
>>> 1 / 10 * 3 0.30000000000000004 >>> decimal.Decimal('1') / 10 * 3 Decimal('0.3') >>> fractions.Fraction('1') / 10 * 3 Fraction(3, 10)
My question is: if I have Fraction , what is the best way to convert it to Decimal ?
Unfortunately, the obvious solution does not work:
>>> decimal.Decimal(fractions.Fraction(3, 10)) Traceback (most recent call last): ... TypeError: conversion from Fraction to Decimal is not supported
I am using this code now:
>>> decimal.Decimal(float(fractions.Fraction(3, 10))) Decimal('0.299999999999999988897769753748434595763683319091796875')
Now that I really produce this value, any amount of rounding converts it to 0.3, and I do this conversion just before exiting (all basic math is done using Fraction ). However, it seems a little silly to me that I cannot get Decimal('0.3') from Fraction(3, 10) . Any help would be appreciated!
python decimal standard-library fractions
Dan passaro
source share