Python Round Float

python round float

In Python, the round() function is used to round off decimal numbers to a specific number of decimal places. It is commonly used when dealing with floating-point numbers that have a large number of decimal places. The round() function takes two arguments. The first argument is the number that needs to be rounded off, and the second argument is the number of decimal places to which the number should be rounded off.

Syntax of Python Round Float

The syntax of the round() function is as follows:

round(number, ndigits)

The number argument is the number that needs to be rounded off, and the ndigits argument is the number of decimal places to which the number should be rounded off.

Examples of Python Round Float

Here are some examples of how to use Python round float:

Example 1: Round off to the nearest integer

x = 4.6
print(round(x))

Output:

5

In this example, we rounded off the number 4.6 to the nearest integer using the round() function.

Example 2: Round off to a specific number of decimal places

x = 3.141592653589793238
print(round(x, 2))

Output:

3.14

In this example, we rounded off the number 3.141592653589793238 to two decimal places using the round() function.

Example 3: Round off to the nearest multiple of 10

x = 47
print(round(x, -1))

Output:

50

In this example, we rounded off the number 47 to the nearest multiple of 10 using the round() function.

Example 4: Round off negative numbers

x = -1.23456789
print(round(x, 3))

Output:

-1.235

In this example, we rounded off the negative number -1.23456789 to three decimal places using the round() function.

Example 5: Round off using mathematical functions

import math

x = 2.71828
print(math.ceil(x))
print(math.floor(x))
print(math.trunc(x))

Output:

3
2
2

In this example, we used the ceil(), floor(), and trunc() functions from the math module to round off the number 2.71828 to the nearest integer, round down to the nearest integer, and truncate the decimal part, respectively.

Conclusion

Python round float is a useful function when working with decimal numbers. It allows you to round off a number to a specific number of decimal places or to the nearest integer or multiple of 10. In this tutorial, we discussed the syntax and usage of the Python round float function with several examples. By mastering this function, you can easily work with floating-point numbers in your Python applications.