Python 2.7: rounding down instead of rounding up

Tiffany Morris

Rounding up seems easy but I can't figure out how to round down.

Using this code:

def __str__(self):
        return'x = %.2f,y = %.2f'%(self.x,self.y)

Output:

>>> p1 = Point(1.216,3.4582)
>>> print p1
x = 1.22,y = 3.46

How can I return x = 1.21 instead of 1.22 and y = 3.45 instead of 3.46?

DBrowne

You could do something like:

return 'x = %.2f, y = %.2f' % (int(self.x * 100)/100.0, 
                               int(self.y * 100)/100.0)

Note that this always rounds towards zero rather than rounding down. This is only important if you need to handle negative values. (i.e. -2.467 will display as -2.46)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related