The best way to convert fractions. Fraction in decimal.

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!

+8
python decimal standard-library fractions
source share
1 answer

How about leaving the fraction division on Decimal() own?

 def decimal_from_fraction(frac): return frac.numerator / decimal.Decimal(frac.denominator) 

This is what Fraction.__float__() does (just divide the numerator by the denominator), but by turning at least one of the two values ​​into a Decimal object, you get output control.

This allows you to use the Decimal context:

 >>> decimal_from_fraction(fractions.Fraction(3, 10)) Decimal('0.3') >>> decimal_from_fraction(fractions.Fraction(1, 55)) Decimal('0.01818181818181818181818181818') >>> with decimal.localcontext() as ctx: ... ctx.prec = 4 ... decimal_from_fraction(fractions.Fraction(1, 55)) ... Decimal('0.01818') 
+11
source share

All Articles