round() function in python is used to round a floating number to the specified number of decimal places.
The general syntax for the round()
function is
round(number, ndigits)
round() Parameters
Parameter | Condition | Description |
number | Required | Number to round |
ndigits | Optional | Number of decimal digits to round to. Default is None. |
If ndigits
is not provided then the number is rounded to the nearest integer.
Let’s see some examples.
Example: Round numbers in Python using round()
number = 4.658 print(round(number,2)) # output 4.66 number = 4.658 print(round(number,1)) # output 4.7 number = 4.658 print(round(number)) # output 5 number = 3.608 print(round(number,2)) # output 3.61 number = 3.608 print(round(number,1)) # output 3.6
Round To Ten’s or Hundred’s
We can also specify a negative value for ndigits
. In this case, the number gets rounded to ten’s or hundreds.
Let’s see some examples of the same.
number = 41 print(round(number,-1)) # output 40 number = 46 print(round(number,-1)) # output 50 number = 52 print(round(number,-1)) # output 50 number = 98 print(round(number,-2)) # output 100 number = 105 print(round(number,-2)) # output 100
Rounding Up or Down
If you want to round number explicitly up or down then use ceil() or floor() function of python’s math module.
import math # Round a number up x = math.ceil(4.2) print(x)
output
5
import math # Round a number up x = math.floor(4.2) print(x)
output
4
If Hope now rounding number in python would be easy for you. If you have any suggestions or doubts then comment below.