Python round() function


The round() function in Python is used to round a floating-point number to a specified number of decimal places, or to the nearest integer if no decimal places are specified.

Syntax

round(number, ndigits)
  • number: The number you want to round.
  • ndigits (optional): The number of decimal places to round to. If omitted, it defaults to 0, meaning the number will be rounded to the nearest integer.

Return Value

  • If ndigits is provided, it returns the number rounded to the specified decimal places.
  • If ndigits is omitted or 0, it returns the nearest integer.
  • For negative numbers, it rounds towards zero (also known as rounding half to even).

Examples

  1. Rounding to the nearest integer (default behavior):

    print(round(4.6)) # Output: 5 print(round(4.3)) # Output: 4
  2. Rounding to specific decimal places: You can specify the number of decimal places using the ndigits argument:

    print(round(3.14159, 2)) # Output: 3.14 print(round(3.14159, 3)) # Output: 3.142
  3. Rounding with ndigits = 0 (explicit integer rounding):

    print(round(9.99, 0)) # Output: 10.0
  4. Rounding negative numbers:

    print(round(-4.6)) # Output: -5 print(round(-4.3)) # Output: -4
  5. Rounding to negative decimal places: You can also round numbers to negative decimal places, which rounds to the nearest tens, hundreds, etc.

    print(round(12345, -1)) # Output: 12350 print(round(12345, -2)) # Output: 12300

How It Handles Halfway Cases (Banker's Rounding)

The round() function uses a technique called rounding half to even, also known as banker's rounding. This means that when a number is exactly halfway between two integers (like 2.5 or 3.5), it rounds towards the nearest even number.

Example:

print(round(2.5)) # Output: 2 (rounds to even) print(round(3.5)) # Output: 4 (rounds to even)

Summary

  • round() is used to round numbers to a specified number of decimal places.
  • It uses rounding half to even for numbers that are exactly halfway between two values.
  • Can handle rounding both positive and negative numbers.