Saturday, May 09, 2009

Format numbers in Python

We have already been discussing rounding of numbers in Python in a precious post, also I have been discussing the use of the math.ceil and math.floor functions that can be used in Python. However, there are some more places where rounding is done and that is when you use number formats when you print something.

for example we have the value 30.6475 which we would like to print to the screen as a dollar value like $30.65. What we could do is a rounding of the value 30.6475 and print it in combination with the dollar sign. It can also be done as shown below with a command like print "$%.02f" %30.6475

the 2f is used to define the amount of numbers behind the point. so we can make it for example 3 if we want a output like $30.648.

1 comment:

Anonymous said...

this is my first visit to ur Blog , but u have impressed me since paython is not of expertise list ,..