Why does Math.floor return a double?

前端 未结 6 2017
-上瘾入骨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:24

    Just as there is an integer and a floating point division in Java, there are integer and floating point ways to do floor:

    double f = Math.floor(x);
    

    or

    int k = (int) x; 
    

    but you always need to be careful with using floor with finite precision arithmetic: your calculation of x may yield something like 1.99999999 which will be floored to 1, not 2 by both forms. There are many algorithms out there that need to work around this limitation to avoid producing wrong results for some input values.

提交回复
热议问题