Python <2.7
"%.15g" % f
Or in Python 3.0:
format(f, ".15g")
Python 2.7+, 3.2+
Just pass the float to Decimal constructor directly, like this:
from decimal import Decimal
Decimal(f)
Answer from jfs on Stack OverflowPython <2.7
"%.15g" % f
Or in Python 3.0:
format(f, ".15g")
Python 2.7+, 3.2+
Just pass the float to Decimal constructor directly, like this:
from decimal import Decimal
Decimal(f)
I suggest this
>>> a = 2.111111
>>> a
2.1111110000000002
>>> str(a)
'2.111111'
>>> decimal.Decimal(str(a))
Decimal('2.111111')
What's different between Decimal and Floating point numbers in Python?
numpy - converting a float to decimal type in Python - Stack Overflow
How to do Decimal to float conversion in Python? - Stack Overflow
Convert dict floats to decimals
Videos
I'm confused in differentiating between these two types of numbers. I'm a newbie.
Can anyone here please explain this?
Try doing decimal.Decimal.from_float(frac[i])
Depending where your fractions are coming from, you may find it ideal to use the fractions module. Some examples from the docs:
>>> from fractions import Fraction
>>> Fraction(16, -10)
Fraction(-8, 5)
>>> Fraction(123)
Fraction(123, 1)
>>> Fraction()
Fraction(0, 1)
>>> Fraction('3/7')
Fraction(3, 7)
>>> Fraction(' -3/7 ')
Fraction(-3, 7)
>>> Fraction('1.414213 \t\n')
Fraction(1414213, 1000000)
>>> Fraction('-.125')
Fraction(-1, 8)
>>> Fraction('7e-6')
Fraction(7, 1000000)
>>> Fraction(2.25)
Fraction(9, 4)
>>> Fraction(1.1)
Fraction(2476979795053773, 2251799813685248)
>>> from decimal import Decimal
>>> Fraction(Decimal('1.1'))
Fraction(11, 10)
You can also perform all of the regular arithmetic operations; if the result can't be expressed as a fraction, it will be converted to a float:
>>> Fraction(3, 4) + Fraction(1, 16)
Fraction(13, 16)
>>> Fraction(3, 4) * Fraction(1, 16)
Fraction(3, 64)
>>> Fraction(3, 4) ** Fraction(1, 16)
0.982180548555
There are two methods:
float_number = float(decimal_number)float_number = decimal_number * 1.0
First one using the built in function and second one without any function, but take care about the 1.0 not 1 as it should be float so the result will be float.
Just use float:
float_number = float(decimal_number)