round() returns different result depending on the number of arguments

Question:

While using the round() function I noticed that I get two different results depending on whether I don’t explicitly choose the number of decimal places to include or choosing the number to be 0.

x = 4.1
print(round(x))
print(round(x, 0))

It prints the following:

4
4.0

What is the difference?

Asked By: Peter Hofer

||

Answers:

When you specify the number of decimals, even if that number is 0, you are calling the version of the method that returns a float. So it is normal that you get that result.

Answered By: Wazaki

The round() function in Python takes two parameters:

  1. number – number to be rounded
  2. number of digits (optional) – the number of digits up to which the given number is to be rounded.

Whenever you use the second parameter, Python automatically converts the data type of the return value to float. If you don’t use the second optional parameter then the data type remains an integer.

Therefore, it is 4.0 when the parameter is passed and 4 when it isn’t.

Answered By: codelyzer

The round function returns an integer if the second argument is not specified, else the return value has the same type as that of the first argument:

>>> help(round)
Help on built-in function round in module builtins:

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.

    The return value is an integer if ndigits is omitted or None. Otherwise
    the return value has the same type as the number. ndigits may be negative.

So if the arguments passed are an integer and a zero, the return value will be an integer type:

>>> round(100, 0)
100
>>> round(100, 1)
100

For the sake of completeness:

Negative numbers are used for rounding before the decimal place

>>> round(124638, -2)
124600
>>> round(15432.346, -2)
15400.0
Answered By: Aniket Navlur

I think that it is worth to mention, that you can encounter not only round(int) or round(float), but for example: round(class ‘numpy.float64’). In that case round will not return integer even when “ndigits is omitted or None.” (like Built-in Functions documentation says), but the type of class numpy.float64. I analyzed code example and bumped at round(x) prints “10.0” in python 3.7.3

Answered By: Michał Woźniak
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.