Reputation: 2002
Does an analogue to Java's Math.rint
exist in Python?
If not, how can I achieve the same result?
Upvotes: 1
Views: 1776
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:
Return the floating point value
x
rounded ton
digits after the decimal point. Ifn
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 minusn
; if two multiples are equally close, rounding is done away from 0 (so. for example,round(0.5)
is1.0
andround(-0.5)
is-1.0
).Note
The behavior of
round()
for floats can be surprising: for example,round(2.675, 2)
gives2.67
instead of the expected2.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
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