Round a Floating Point Number Down to the Nearest Integer?

前端 未结 12 1431
悲哀的现实
悲哀的现实 2020-12-02 13:45

As the title suggests, I want to take a floating point number and round it down to the nearest integer. However, if it\'s not a whole, I ALWAYS want to round down the variab

相关标签:
12条回答
  • 2020-12-02 14:23

    To get floating point result simply use:

    round(x-0.5)
    

    It works for negative numbers as well.

    0 讨论(0)
  • 2020-12-02 14:25

    If you working with numpy, you can use the following solution which also works with negative numbers (it's also working on arrays)

    import numpy as np
    def round_down(num):
        if num < 0:
            return -np.ceil(abs(num))
        else:
            return np.int32(num)
    round_down = np.vectorize(round_down)
    

    round_down([-1.1, -1.5, -1.6, 0, 1.1, 1.5, 1.6])
    > array([-2., -2., -2.,  0.,  1.,  1.,  1.])
    

    I think it will also work if you just use the math module instead of numpy module.

    0 讨论(0)
  • 2020-12-02 14:27

    Just make round(x-0.5) this will always return the next rounded down Integer value of your Float. You can also easily round up by do round(x+0.5)

    0 讨论(0)
  • 2020-12-02 14:27

    Don't know if you solved this, but I just stumble upon this question. If you want to get rid of decimal points, you could use int(x) and it will eliminate all decimal digits. Theres no need to use round(x).

    0 讨论(0)
  • 2020-12-02 14:28

    It may be very simple, but couldn't you just round it up then minus 1? For example:

    number=1.5
    round(number)-1
    > 1
    
    0 讨论(0)
  • 2020-12-02 14:33

    a lot of people say to use int(x), and this works ok for most cases, but there is a little problem. If OP's result is:

    x = 1.9999999999999999
    

    it will round to

    x = 2
    

    after the 16th 9 it will round. This is not a big deal if you are sure you will never come across such thing. But it's something to keep in mind.

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