The Nearest Integer Function in Python

Techwalla may earn compensation through affiliate links in this story.

Perhaps attesting to its reputation as a powerful and flexible programming language, Python contains many internal libraries to automate common or complex computational and mathematical tasks. The "math library" contains many methods to accomplish typical calculations or operations such as rounding. However, rounding decimals in Python does not round to an integer, but a whole decimal. Converting to integers requires the use of the Python math library along with the use of some built-in conversion libraries.

Python and Rounding

The Python math library offers a package of methods useful for rounding decimal numbers to whole numbers. You can round a number in the traditional way (down to the nearest whole number for fractional parts at .4 or lower, and up for parts .5 and larger) using the "round()" method. The following example shows how to round decimal numbers using the round method:

Video of the Day

f = 5.455 >>>round(f) 5.0 >>>round(f, 2) //rounds to 2 decimals 5.46

Ceiling and Floor Methods

As part of the math library, the "floor()" and "ceil()" methods provide a unique way for rounding decimals that you may find useful in certain calculations. The floor method rounds down to the least nearest whole number toward negative infinity (regardless of the decimal value), and the ceiling method will round up to the nearest whole number toward positive infinity. The following example displays how the two functions work:

import math >>>f = 3.5 >>>g = -3.5 >>>floor(f) 3.0 >>>ceil(3.5) 4.0 >>>floor(g) -4.0 >>>ceil(g) -3.0

Rounding and Integers

The rounding operations illustrated show how these functions work, but they also show a side effect: in Python versions before 3.0, decimals rounded do not round to integers, but decimals. Because of the way decimals are represented by computer architectures, this could cause problems in high-precision calculations where programmers might require integers.You can convert a floating number to an integer using the "int()" method, as in this example:

f = 3.5 >>>round(f) 4.0 >>>int(round(f)) 4

Example Method

Using this knowledge, you can develop a method to round decimals to integers easily. The following examples show brief examples of methods that determine the floor and ceiling of a number as an integer, and another that rounds to a user-designated decimal place (or an integer):