89DEVs

Python: How to round to nearest integer?

Use the built-in round() function or numpy.round() to round to the nearest integer in Python.

The number of decimals can be specified in the second argument of the round() function. This argument is optional and if it is not specified it defaults to 0. Then the round() function rounds to the next whole number.

round positive value to next integer

To round a number to the next integer we call the round() function without specifying the second, optional argument. # round positive value to next integer myFloat = 2.49 rounded = round(myFloat) print(rounded) The float value is rounded to the next integer, in this case 2. 2

round negative value to next integer

It works the same way for negative numbers. # round negative value to next integer myFloat = -2.49 rounded = round(myFloat) print(rounded) The float value is rounded to the next integer, in this case -2. -2

round to next integer with numpy

In case you're already using numpy in your code it might be easier to use numpy. The main difference between the built-in round() function and the numpy round() method is that the built-in function returns an integer while numpy returns a float value. It still rounds to the next integer though. # round to next integer using numpy import numpy myFloat = 2.49 rounded = numpy.round(myFloat) print(rounded) numpy returns the rounded value as float, not as integer. 2.0 Of course it's simple to get an integer by combining numpy.round() with the built-in int() function. # round to next integer using numpy import numpy myFloat = 2.49 rounded = int(numpy.round(myFloat)) print(rounded) Now the result is returned as integer, in this case 2. 2

Other rounding operations in Python

Python offers a variety of other rounding operations: To round up use math.ceil() or numpy.ceil() methods. To round down use the int() function or the math.floor() method. To round to 2 decimals use the built-in round() function. To round to 5 (or any other number) use a custom function.

                
        

Summary


Click to jump to section