Number round floats Using Python — pythonpip.com

This python tutorial help to round float number using python 3. The 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 −

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 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

Originally published at https://www.pythonpip.com on October 29, 2022.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Parvez Alam

Hey, I am Parvez Alam. A software developer since 2009. I love learning and sharing knowledge. https://www.phpflow.com/