Round number to nearest integer

前端 未结 11 2109
傲寒
傲寒 2020-11-27 12:32

I\'ve been trying to round long float numbers like:

32.268907563;
32.268907563;
31.2396694215;
33.6206896552;
...

With no success so far. I

11条回答
  •  失恋的感觉
    2020-11-27 13:20

    For positives, try

    int(x + 0.5)
    

    To make it work for negatives too, try

    int(x + (0.5 if x > 0 else -0.5))
    

    int() works like a floor function and hence you can exploit this property. This is definitely the fastest way.

提交回复
热议问题