When we work with numbers in Python, there might be a situation when we want to turn a decimal fraction into a whole number.
To replace a value with another number that is almost equal to the original number is called rounding to the nearest value. For example, there is a number 2.5; it will become either 2 or 3 after rounding. The rounded values are much easy to interpret.
Python offers a built-in function for rounding the numbers, i.e., round( ). It returns a floating-point value. Also, Python has a math module for using ceiling and floor functions to get the task done.
In this article, we will learn different rounding methods and also how to use the round( ) function in Python. There will be example code snippets along with the output for the proper understanding.
Table of Contents
Round( ) :
It is a built-in function of Python.
Python’s built-in round returns floating-point numbers up to the specified number of decimal values. If the decimal digits that need to be rounded off are not mentioned, the number gets rounded to the nearest integer.
The syntax is given as:
round ( number, number of decimal )
- Number: the number we want to round off
- Number of decimal: number of decimal places up to which we want to round off. It is optional.
print(round(50)) print(round(42.7)) print(round(42.8)) print(round(42.9))
Number of Decimals specified:
print(round(3.885, 2)) print(round(2.837, 2)) print(round(2.823, 2))
x = 2/3 print(x) print(round(x, 3))
This function helps to round up a number up to the next nearest integer. First, import the math module. We can check for negative values as well. The syntax will be:
import math math.ceil ( number )
import math num1= math.ceil(6.3) print(num1) num2= math.ceil(6) print(num2) num3= math.ceil(6.5) print(num3) num4= math.ceil(-0.5) print(num4)
This function helps to round down a number up to the next nearest integer. You first need to import the math library. The syntax is:
import math math.floor ( number )
import math num1= math.floor(6.3) print(num1) num2= math.floor(6) print(num2) num3= math.floor(6.5) print(num3) num4= math.floor(-0.5) print(num4)
The article has discussed three different methods of rounding off a digit. Rounding values help in many different tasks during development. But be sure while rounding the numbers and choosing the proper method. I hope the examples helped understanding the concept.