Home > Enterprise >  Difference between // and round() in Python
Difference between // and round() in Python

Time:07-03

Is there a difference between using // (Integer Division) and the built-in round() function in Python? If I understand correctly, both will round to the nearest Integer but I'm unsure if the behaviour of both the function and the operator is exactly the same at all times. Can someone clarify? Can both of them be used "interchangeably"?

CodePudding user response:

// is floor division, round rounds to nearest. // stays integer at all times, round using / converts to float before rounding back, which might not work at all for large enough ints, and can lose precision for smaller (but still large) ints.

If you need floor division of ints, always use // (you can do ceiling division too, with -(-num // div)). It's always correct, where round (and math.floor) might not be (for ints exceeding about 53 bits). round is more configurable (you can round off to a specified number of decimal places, including negative decimal places to round off to the left of the decimal point), but you want to avoid converting to float at all whenever you can.

CodePudding user response:

>>> 5 // 2
2
>>> round(5 / 2)
2
>>> round(5 / 2, 1)
2.5
>>>

The round function gives you more control over the precision of rounding. The // operator provides the floor (rounds down) of dividing the two.

Consider also:

>>> round(20 / 3)
7
>>> 20 // 3
6
>>>
  • Related