2

I want to round some int numbers but I came across with the strange feature of round() for example

round(2.1) = 2

round(2.5) = 2 #it rounds to ceil

round(2.7) = 3

it rounds differently with the odd number as follow

round(5.1) = 5

round(5.5) = 6 #it rounds to floor

round(5.7) = 6

it rounds the X.5 to the floor with the x = even numbers but with the X = odd numbers it rounds to the ceil

I want to ask what is the advantage of this round? and where can I use it in our examples ? or what is its usage?

Mehdi dev
  • 33
  • 6

1 Answers1

0

Looks like if it's close it goes to the even option. From the documentation https://docs.python.org/3/library/functions.html#round

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as number.

For a general Python object number, round delegates to number.round.

Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

avenmia
  • 2,015
  • 4
  • 25
  • 49