Why does Math.floor return a double?

前端 未结 6 2021
-上瘾入骨i
-上瘾入骨i 2020-12-13 23:05

Official Javadoc says that Math.floor() returns a double that is \"equal to a mathematical integer\", but then why shouldn\'t it return an in

6条回答
  •  我在风中等你
    2020-12-13 23:18

    Others have told you the why, I'm going to tell you how to round correctly given you want to do this. If you are only going to use positive numbers, then you can use this statement:

    int a=(int) 1.5;
    

    However, the (int) always rounds towards 0. Thus, if you want to do a negative number:

    int a=(int) -1.5; //Equal to -1
    

    In my case, I didn't want to do this. I used the following code to do the rounding, and it seems to handle all of the edge cases well:

    private static long floor(double a)
    {
        return (int) Math.floor(a);
    }
    

提交回复
热议问题