Round with integer division

前端 未结 6 693
情书的邮戳
情书的邮戳 2021-01-07 17:47

Is there is a simple, pythonic way of rounding to the nearest whole number without using floating point? I\'d like to do the following but with integer arithmetic:

6条回答
  •  北海茫月
    2021-01-07 18:15

    Simply take care of the rounding rule before you ever divide. For the simplest round-half-up:

    if total % surplus < surplus / 2:
        return total / surplus
    else:
        return (total / surplus) + 1
    

    Tweak a little bit if you need to do a proper round-to-even.

提交回复
热议问题