Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 840
Peter Hofer Avatar asked Oct 19 '18 13:10

Peter Hofer


People also ask

How many arguments does the ROUND function take?

The Python round function takes up to two arguments: A floating point number to round. A number of decimals to round the number to.

What the round () function does?

The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.

What is the return value of round () function?

round() The Math. round() function returns the value of a number rounded to the nearest integer.

What does the ROUND function do in R?

round() function in R Language is used to round off values to a specific number of decimal value.


2 Answers

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 
like image 185
Aniket Navlur Avatar answered Oct 06 '22 00:10

Aniket Navlur


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.

like image 39
Wazaki Avatar answered Oct 06 '22 00:10

Wazaki