round() function in python

The round() built-in function has a syntax of round (flt,ndig=0). It normally rounds a floating point number to the nearest integral number and returns that result (still) as a float. When the optional third ndig option is given, round() will round the argument to the specific number of decimal places.

>>> round(3)
>>> round(3.45)
>>> round(3.4999999)
>>> round(3.499999,1)
>>> round(-3.5)
>>> round(-3.4)
>>> round(-3.49)
>>> round(-3.49,1)

Note that the rounding performed by round() moves away from zero on the number line, i.e., round(.5) goes to 1 and round(-.5) goes to -1. Also, with functions like int(), round(), and math.floor(), all may seem like they are doing the same thing; it is possible to get them all confused. Here is how you can differentiate among these:
int() chops off the decimal point and everything after (a.k.a. truncation).
floor() rounds you to the next smaller integer, i.e., the next integer moving in a negative direction (towards the left on the number line).
round() (rounded zero digits) rounds you to the nearest integer period.


You may also like...

No © Loop and Break