Sunday, May 03, 2009

Rounding numbers in Python

A couple of post ago I was talking about int and float variables and I showed how you can play with numbers and variables. When working with floating point variables one of the things you most likely will be doing at some point is rounding. when you have a float variable holding a value like 123.783635 you most likely do not want to present this in this form to the users, you most likely want to represent this like 123.78. In this case you will be needing the round function.

In this case we will be executing a command like round(123.783635, 2) because we like to have to numbers behind the digit. if we would like to have 1 number behind the digit we change the last number, something like; round(123.783635, 1).

This is quite easy and strait forward, however there are some more nice tricks you can do with the round function in Python. For example if we have the number 1259 and we like to round it to 1300 we can also use the round function by executing something like round(1259, -2). You can just play around with it some more to get a good idea on how it is working like in the example below.



Post a Comment