Python 3 – Number round() Method
Python is one of the most popular programming languages that is widely used for web development, scientific computing, and data analysis. Python has many number methods that make it easy to manipulate and perform mathematical operations on numbers. One of the number methods in Python is the round()
method, which is used to round off floating-point numbers (decimal numbers) to a specified number of digits. In this article, we’ll explore how to use the round()
method in Python 3.
The syntax for using the round()
method is pretty straightforward. It takes one or two arguments, and it returns a rounded value.
Syntax
round(number, ndigits=None)
Parameters
The round()
method takes two parameters:
number
– the number to be rounded off.ndigits
(optional) – the number of digits to round off the number to. If omitted, it defaults to 0, meaning it will round off the number to the nearest integer.
Return value
The round()
method returns a rounded floating-point number.
Examples
Let’s look at some examples of using the round()
method in Python 3.
Example 1: Rounding off to the nearest integer
To round off a floating-point number to the nearest integer, we can simply call the round()
method with one argument, which is the number we want to round off. For example:
x = 3.14
rounded_num = round(x)
print(rounded_num) # Output: 3
In this example, we’ve rounded off the floating-point number 3.14
to the nearest integer, which is 3
.
Example 2: Rounding off to the nearest specified digit
The round()
method can also be used to round off a number to a specified number of digits after the decimal point. To do this, we simply pass the number of digits we want to round off to as the second argument. For example:
x = 3.14159
rounded_num = round(x, 2)
print(rounded_num) # Output: 3.14
In this example, we’ve rounded off the floating-point number 3.14159
up to two decimal places, resulting in 3.14
.
Example 3: Rounding off negative numbers
The round()
method can also be used to round off negative numbers. When rounding off negative numbers, the round()
method rounds them off towards 0. For example:
x = -3.25
rounded_num = round(x)
print(rounded_num) # Output: -3
rounded_num = round(x, 1)
print(rounded_num) # Output: -3.2
In this example, we’ve rounded off the floating-point number -3.25
without providing a second argument to round off to the nearest integer. As a result, the number is rounded off towards 0, resulting in -3
. However, when we round off -3.25
up to one decimal place, we get -3.2
.
Conclusion
The round()
method is a useful number method in Python that simplifies the process of rounding off floating-point numbers in programs. We’ve seen how to use the round()
method to round off numbers up to a specified number of digits, including rounding off negative numbers towards 0. With this knowledge, you can now use the round()
method in your programs to round off numbers as required.