How to prevent rounding in python
Question:
suppose if a variable has a float value, and if i re-assign the same variable with an another float value it will round the fractional part of the value with respect to the no of fractional part in first value, how can i prevent that
eg:
wav=10.456878798
print wav
wav=10.555546877796546
print wav
10.456878798
10.5555468778
Answers:
The problem is not with Python. See print statement prints 10 decimal places of a fraction even though it has more. Just check your variable in python shell, it shall give you the entire value.
>>> wav = 10.232483243243243
>>> print wav
10.2324832432
>>> wav
10.232483243243243
You can do the following and set the precision :
$ cat test.py
a = 10.456878798
print "{0:.2f}".format(a)
a = 10.555546877796546
print "{0:.15f}".format(a)
The above will print you :
$ python test.py
10.46
10.555546877796546
Hope this helps.
None of the solutions provided worked. So I decided to search the Standard Library and found a very useful formula. In order to do so you need to import decimal from the standard library and define the precision of the fractional part as follow. This way you will have 28 digits in the fraction part!
from decimal import *
getcontext().prec = 28
after that in the python shell, you would find as follow:
Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')
y = 3.1415926535897932384626
y = "{:.6f}".format(y)
y = str(y)
y = y[:-2]
print(y)
suppose if a variable has a float value, and if i re-assign the same variable with an another float value it will round the fractional part of the value with respect to the no of fractional part in first value, how can i prevent that
eg:
wav=10.456878798
print wav
wav=10.555546877796546
print wav
10.456878798 10.5555468778
The problem is not with Python. See print statement prints 10 decimal places of a fraction even though it has more. Just check your variable in python shell, it shall give you the entire value.
>>> wav = 10.232483243243243
>>> print wav
10.2324832432
>>> wav
10.232483243243243
You can do the following and set the precision :
$ cat test.py
a = 10.456878798
print "{0:.2f}".format(a)
a = 10.555546877796546
print "{0:.15f}".format(a)
The above will print you :
$ python test.py
10.46
10.555546877796546
Hope this helps.
None of the solutions provided worked. So I decided to search the Standard Library and found a very useful formula. In order to do so you need to import decimal from the standard library and define the precision of the fractional part as follow. This way you will have 28 digits in the fraction part!
from decimal import *
getcontext().prec = 28
after that in the python shell, you would find as follow:
Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')
y = 3.1415926535897932384626
y = "{:.6f}".format(y)
y = str(y)
y = y[:-2]
print(y)