How to Round Numbers in Python Language

In this tutorial, we will understand how does rounding off works and how to implement it using Python language.

In mathematics, rounding off a number means making a number easier to compute and use. For Example, let’s say a person’s weight is 76.98 Kg. Now, It becomes a difficult task to use this number so instead, we say the person weighs 77 Kg. We rounded off the number to the nearest multiple of 10. Yes, it gives an approximation of the number which can be an inaccurate representation of the number but it makes it easier to use.

Now, Let’s see how we can do this using Python…

Python being a new age programming language provides us with a built-in function to round a number called round().

The syntax for which is:

round(number, ndigits)

where the parameters are:

  1. number i.e. the digit to want to round off.
  2. ndigits i.e. to what decimal places you want to round it off.

Let’s see some examples, and understand.

Example 1:

Suppose we want to round off 98.666 and get the ru

print(round(98.666)) 
print(round(98.666,1)) 
print(round(98.666,2)) 
print(round(98.666,-1))

Here, the output will be:

99
98.7
98.67
100.0

Example 2:

Suppose we want to round off 98.444

print(round(98.444)) 
print(round(98.444,1)) 
print(round(98.444,2)) 
print(round(98.444,-1))

Here, the output will be:

98
98.4
98.44
100.0

Here, 98.444 is closer to 98 while 98.666 is closer to 99. Similarly, 98.666 is closer to 98.7 while 98.444 is closer to 98.4, and so on…

Note: By default, ndigits parameter is set to 0. And if we use a negative value for ndigits, we will be rounding off the number towards the left of the decimal point.

Leave a Reply

Your email address will not be published. Required fields are marked *