Search code examples
pythonpython-2.7rounding

How to prevent rounding in python


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

Solution

  • 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.