OKPEDIA PYTHON EN MATEMATICA

How to round a number in python

To round a decimal number in Python use the round() function

round(x,n)

The function has two parameters

  • The first parameter (x) is the decimal number to round.
  • The second parameter (n) are the decimal places of the rounded number.

The function returns a real number rounded by approximation.

What is rounding by approximation? The function rounds down the number if the last digit is less than 5 or rounds up the number if the last digit is equal to or greater than 5.
rounding down and rounding up (example)

To always carry out rounding by truncation, use the trunc() function of the math library.

Examples

Example 1

This script rounds the number by approximation to one decimal place.

x=3.84
y=round(x,1)
print(y)

The result is the following

3.8

It is a rounding down because the last useful figure is less than 5.

Example 2

This script rounds the decimal number by approximation to one decimal place.

x=3.95
y=round(x,1)
print(y)

The function returns in output

4.0

It is a rounding up because the last useful figure is greater than-equal to 5.

Example 3

This script rounds the decimal number to approximate zero decimal places.

x=2.91
y=round(x,0)
print(y)

The output result is the following:

3.0

The round () function returns a real number rounded up.

https://how.okpedia.org/en/python/how-to-round-a-number-in-python


Report us an error or send a suggestion to improve this page


Python Mathematics


FacebookTwitterLinkedinLinkedin