Skip to main content
Number round floats Using Python

Number round floats Using Python

This Python tutorial helps to round float numbers using Python 3. Python has a built-in function round() in Python. It returns x rounded to n digits from the decimal point.

Round Float Number Using round()

The round() function will round the floating-point number to n decimal places and will return the result.

Syntax

Following is the syntax for the round() method −

round( x [, n] )

Where parameters are:

x − This is a numeric expression.
n − Represents the number of digits from the decimal point up to which x is to be rounded. The default is 0.

If the number after the decimal place is given

  • >=5 than + 1 will be added to the final value.
  • <5 than the final value will return as it is up to the decimal places mentioned.

Return Value :

This method returns x rounded to n digits from the decimal point.

Example:

The following example shows the usage of round() method.

print ("round(30.54233) : ", round(30.54233))
print ("round(30.54233,1) : ", round(30.54233,1))
print ("round(30.54233, 2) : ", round(30.54233, 2))

Output:

round(30.54233) :  31
round(30.54233,1) :  30.5
round(30.54233, 2) :  30.54


** Process exited - Return Code: 0 **
Press Enter to exit terminal

Round a Float Number Using f-string

You can create a formatted string literal to round a float to n decimal places. The formatted string literal will round the float to n decimal places and will return the result.

Example: Rounding Float Numbers

In the below python program, we will see how rounding on floating numbers

my_float = 30.54233

result = f'{my_float:.2f}'
print(result)

Output:

30.54


** Process exited - Return Code: 0 **
Press Enter to exit terminal

Round Float Numpy Arrays

We can make use of numpy module and use numpy.round() or numpy.around() method to round the float number.

round float Number Using numpy.round()

Let’s take the sample example as shown in below.

import numpy as np
arr = [-0.53124, 52.48989, 23.6533]
arr1 = np.round(arr, 2)
print(arr1)

Output:

[-0.53 52.49 23.65]


** Process exited - Return Code: 0 **
Press Enter to exit terminal

Leave a Reply

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