How to properly round-up half float numbers? How to properly round-up half float numbers? python python

How to properly round-up half float numbers?


The Numeric Types section documents this behaviour explicitly:

round(x[, n])
x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.

Note the rounding half to even. This is also called bankers rounding; instead of always rounding up or down (compounding rounding errors), by rounding to the nearest even number you average out rounding errors.

If you need more control over the rounding behaviour, use the decimal module, which lets you specify exactly what rounding strategy should be used.

For example, to round up from half:

>>> from decimal import localcontext, Decimal, ROUND_HALF_UP>>> with localcontext() as ctx:...     ctx.rounding = ROUND_HALF_UP...     for i in range(1, 15, 2):...         n = Decimal(i) / 2...         print(n, '=>', n.to_integral_value())...0.5 => 11.5 => 22.5 => 33.5 => 44.5 => 55.5 => 66.5 => 7


For example:

from decimal import Decimal, ROUND_HALF_UPDecimal(1.5).quantize(0, ROUND_HALF_UP)# This also works for rounding to the integer part:Decimal(1.5).to_integral_value(rounding=ROUND_HALF_UP)


You can use this:

import mathdef normal_round(n):    if n - math.floor(n) < 0.5:        return math.floor(n)    return math.ceil(n)

It will round number up or down properly.