Wednesday, March 11, 2015

round() Built-in Function In Python - Python Numbers - Python Tutorial

round() built-in function in Pythonround() Built-in Function In Python


In our previous Python tutorial, we looked at some weird numbers you can get when you doing math with floating point numbers in Python. We also explained that this is not some bug that it has to do with the underlying c language and how it handles floating point numbers. C language converts floating point numbers to fractions and when those fractions are called by Python they again are converted to float and the conversion between a float and fraction are not always accurate.

We also discussed that one of the ways around this minor issue is using a built-in function in Python called round(). Round() will round the floating point number to a certain number to the right of the decimal which we can control in the syntax. To get started with round() let’s look at the syntax for the round() built-in function in Python.


round() Syntax


round(First Argument, Second Argument)


First Argument


This is where we input the float that we want to round.


Second Argument


The second argument is after the comma. This location is where we can declare how many numbers after the decimal we want to use. If we give no second argument then the argument defaults to zero.


round() Examples


#Round Examples

#From the previous tutorial
>>> 7.6 + 8.7
16.299999999999997

#How to fix the above example
>>> round(7.6 + 8.7, 1)
16.3

#Another example
>>> a = 0.1 + 0.2
>>> a
0.30000000000000004
>>> round(a,1)
0.3

#How about more numbers after the decimal
>>> b = 9.5434 * 983245.8943
>>> b
9383508.86766262
>>> round(b, 4)
9383508.8677

Well that is pretty easy use and fix the occasional inaccuracy in Python numbers. Well the round() built-in function in Python does have its own issues.  Take a look at this example.


Round() Issues


#Round() Issues

#This doesn't make sense
>>> round(2.675, 2)
2.67

#Now you are probably even more confused
>>> round(8.875, 2)
8.88

Well now that we confused you a bit this comes back to the previous tutorial where the underlying c language and how it converts floats to fractions and back again. Not every float can be displayed properly. In this tutorial, we saw where round() could help and we also saw where round() could hurt a bit.We will look at the decimal module in the next tutorial and see how that can help us work together with floats.

In this tutorial, we saw how the round() built-in function could help us in most situations but there are times when round() built-in function in Python may not be the best choice. We will look at our other option in the next tutorial. If you have any questions about round() leave a comment below and we will help you.


 



No comments:

Post a Comment