Round to the nearest 500, Python

后端 未结 3 1771
醉酒成梦
醉酒成梦 2021-02-02 12:54

I\'m looking to find a way to round up to the nearest 500.I\'ve been using:

math.ceil(round(8334.00256 + 250, -3))

Whereby I have a value from

相关标签:
3条回答
  • 2021-02-02 12:58

    Scale, round, unscale:

    round(x / 500.0) * 500.0
    

    Edit: To round up to the next multiple of 500, use the same logic with math.ceil() instead of round():

    math.ceil(x / 500.0) * 500.0
    
    0 讨论(0)
  • 2021-02-02 12:59

    I personally find rounding a but messy. I'd rather use:

    (x+250)//500*500
    

    // means integer division.

    EDIT: Oh, I missed that you round "up". Then maybe

    -(-x//500)*500
    
    0 讨论(0)
  • 2021-02-02 13:15

    Maybe something like this:

    round(float(x) / 500) * 500
    

    The "float" conversion is unnecessary if you are using Python 3 or later, or if you run the statement from __future__ import division for sane integer division.

    0 讨论(0)
提交回复
热议问题