defining precision in python(2.6) division

10,019

Solution 1

"%0.2f" % yournumber

As you said you don't want a rounded number, you might want to try

def twoDigits(x):
    return int(100*x)/100.0

Solution 2

The number are stored as binary floating point. If you need to show just two digits, you can turn the float into a string and control the number of digits displayed using printf like syntax.

mystring = "%.2f" % (x/y)

This will limit the string to have only 2 digits after the decimal point.

if x/y = 1.876543820098765
mystring = "1.88"

Solution 3

f = 1.876543820098765
print f
print round(f, 2)

>> 1.8765438201
>> 1.88
Share:
10,019
Hossein
Author by

Hossein

Updated on June 04, 2022

Comments

  • Hossein
    Hossein over 1 year

    from future import division To perform a division in which I need some percision. However, it gives a long number, like:

    1.876543820098765
    

    I only need the the first two numbers after "." => 1.87 How can I do that?