Home Python Page 3 - Python: Count on It

# Floating Points - Python

We touched on how numbers work in Python a while back in the beginning of our series on Python. In the past few tutorials we discussed strings and how to manipulate them and some of the string methods. Here, in this article, we will go over some of the math modules and discuss different uses for numbers in Python.

By: James Payne
Rating:  / 3
February 19, 2008

SEARCH DEV SHED

TOOLS YOU CAN USE

As we discussed way back in one of the beginning tutorials on Python, a floating point refers to a decimal value. Floating points in Python have a size limit of 17 decimal digits, the largest being 1.79769_10308. Any number larger will result in an error, or a line that says: inf (standing for infinity).

Let's take a look at the following float value:

>>> 4.1*9

36.899999999999999

That's a pretty crazy number of digits to the right of the decimal. What if we don't want to see those? We can format our floating points using the str() function, which allows us to display the number as a string:

>>> 4.1*9

36.899999999999999

>>> str(4.1*9)

'36.9'

You can also use the round function to round out the number, like so:

>>> round(4.1*9)

37.0

But what if you have a number such as 52.9 and you want it to return 52.0 instead of 53.0, since technically, it isn't 53.0. Try using round first:

>>> round(52.9)

53.0

As you can see, round makes it 53.0 automatically. So what do we do if we want it to show 52.0 instead? We use the floor module, that's what:

>>> import math

>>> math.floor(52.9)

52.0

Voila! Easy as pie. That you buy in a supermarket and don't actually make yourself.

Of course, if you are in the reverse situation, you can use our pal, the ceil module (short for ceiling) which does the opposite of the floor module:

>>> import math

>>> math.ceil(53.1)

54.0

If you want to control how many decimals are displayed, you can use %f to format it. Let's say you want to see the number 19 as a decimal. Try typing in the following code:

>>> print "%f" % 19

19.000000

As you can see, it has taken your integer, 19, and formatted it as a decimal, giving the result 19.000000. But what if you only wanted two decimal places? Try this:

>>> print "%.2f" % 19

19.00

If you had typed in %.3f, you would have gotten this result:

>>> print "%.3f" %19

19.000

and so forth, up until %.68f.

 >>> More Python Articles          >>> More By James Payne