How can I round this number 838062.5
to 838063
instead of to 838062
, using the round()
function in Python?
Asked
Active
Viewed 118 times
0
-
1The round() function rounds values of .5 towards an even integer (Python Docs, n.d. a). So .5 is round up for positive values and round down for negative values. For instance, both round(0.5) and round(-0.5) return 0, while round(1.5) gives 2 and round(-1.5) gives -2. This Python behaviour is a bit different from how rounding usually goes. ([from here](https://kodify.net/python/math/round-integers/)) – Sergey Kalinichenko Apr 22 '21 at 04:24
-
Does this answer your question? [Round number to nearest integer](https://stackoverflow.com/questions/31818050/round-number-to-nearest-integer) – Sergey Kalinichenko Apr 22 '21 at 04:33
3 Answers
0
The Python documentation for the round()
function explains this interesting phenomenon:
If two multiples are equally close, rounding is done toward the even choice (so, for example, both
round(0.5)
andround(-0.5)
are0
, andround(1.5)
is2
).
While you could use floor and ceiling operations, matching the various cases may be a pain. So, I recommend using the decimal
module, which allows you to always round half-values up.
>>> import decimal
>>> decimal.getcontext().rounding = decimal.ROUND_HALF_UP
>>> n = decimal.Decimal(838062.5)
>>> n
Decimal('838062.5')
>>> round(n)
838062

Jacob Lee
- 4,405
- 2
- 16
- 37
0
All I had to do was add 0.5 and take the floor value:
import math
x = 838062.5 + 0.5
print(math.floor(x))

General Grievance
- 4,555
- 31
- 31
- 45

pakwai122
- 57
- 7