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:
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:
You can also use the round function to round out the number, like so:
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:
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
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
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
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
If you had typed in %.3f, you would have gotten this result:
>>> print "%.3f" %19
and so forth, up until %.68f.
blog comments powered by Disqus