Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 round() Function

Python3 round() Function

Python3 Numbers Python3 Numbers


Description

round() The method returns the rounded value of float x; more precisely, the retained value is the end closer to the preceding digit (round half to even).

It is not recommended for cases requiring high precision.


Syntax

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


round( x [, n]  )

Parameters


Return Value

Returns the rounded value of float x.


Example

The following shows examples of using the round() method:

Example

#!/usr/bin/python3

print

(

"round(70.23456) : "

,

round

(

70.23456

)

)

print

(

"round(56.659,1) : "

,

round

(

56.659

,

1

)

)

print

(

"round(80.264, 2) : "

,

round

(

80.264

,

2

)

)

print

(

"round(100.000056, 3) : "

,

round

(

100.000056

,

3

)

)

print

(

"round(-100.000056, 3) : "

,

round

(

100.000056

,

3

)

)

Running the example above produces:


round(70.23456) :  70
round(56.659,1) :  56.7
round(80.264, 2) :  80.26
round(100.000056, 3) :  100.0
round(-100.000056, 3) :  -100.0

Take a look at an example from the official documentation:

>>> round(2.675, 2) 
2.67

In our expectation the result should be 2.68, but it is 2.67. Why?

This is related to floating-point precision. We know that in a machine a float may not be represented exactly, because when converted into a string of 1s and 0s it may have infinitely many digits, and the machine truncates it. So the number 2.675 stored in the machine is slightly smaller than the actual number. That tiny difference makes it slightly closer to 2.67, so rounding to two decimal places gives 2.67.

Python3 Numbers Python3 Numbers