How to convert float value to another float value with some specified precision using python?
>>> a = 0.1
but actually value of a is
0.10000000000000001
But I need to convert a to 0.1 in float type.
How to convert float value to another float value with some specified precision using python?
>>> a = 0.1
but actually value of a is
0.10000000000000001
But I need to convert a to 0.1 in float type.
It is not possible to have 0.1
exactly when using the float
type, due to how numbers are stored internally. This offsite resources will hopefully explain the internals more easily.
Note that when you use the Python console it may look like you have 0.1 exactly but this is not true, as the code below shows
In [35]: a = 0.1
In [36]: print(a)
0.1 # Looks fine! But wait, let's print with 30 decimal places...
In [37]: print('{:.30f}'.format(a))
0.100000000000000005551115123126 # Uh oh.
This occurs because when printing in the console, only a certain number of decimal places are printed, and for 0.1 this number is such that where it starts to deviate from 0 is outside the range.
Python does have a Decimal
package which can provide support for decimal numbers, as below
import decimal
a = decimal.Decimal('0.1')
print(a)
# 0.1
print('{:.30f}'.format(a))
# 0.100000000000000000000000000000
Note that I've constructed the Decimal
object using the string '0.1'
as opposed to the float 0.1
. This is because if I had used the float then the Decimal
object would have contained the same "errors" that the float has.
How about the round function: Round
You can use formate
function with float and round
function also
>>> a = float(format(0.10000000000000001, '.1f'))
>>> a
0.1
>>> round(0.10000000000000001,2)
0.1