caneta
caneta

Reputation: 2002

Rounding numbers: Java's 'Math.rint' in Python

Does an analogue to Java's Math.rint exist in Python? If not, how can I achieve the same result?

Upvotes: 1

Views: 1776

Answers (2)

agf
agf

Reputation: 176950

Here is an exact workalike for rint for Python 2:

def rint(num):
    """Rounds toward the even number if equidistant"""
    return round(num + (num % 2 - 1 if (num % 1 == 0.5) else 0))

print rint(-1.4) == -1.0
print rint(-1.5) == rint(-2.0) == rint(-2.5) == -2.0
print rint(1.4) == 1.0
print rint(1.5) == rint(2.0) == rint(2.5) == 2.0

In Python 3, round rounds toward even just like rint (thanks @lvc), but on Python 2:

round(x[, n])

Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).

Note

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

Upvotes: 3

Simeon Visser
Simeon Visser

Reputation: 122496

You can use the built-in function round:

  • round(3.5) gives 4.0
  • round(3.4) gives 3.0
  • round(3.6) gives 4.0

Upvotes: 0

Related Questions