Math.ceil 和 Math.floor 返回相同的值

2022-09-02 02:14:29

我有一个双 (23.46)

使用Math.ceil和Math.floor的方法,并将我的双精度解析为这些方法,我得到相同的值返回给我,即23...

我希望它被四舍五入到24.换句话说,如果我有一个15.01的双精度,它仍然应该被四舍五入到16...我该怎么做?


答案 1

无法重现:

public class Test
{
    public static void main(String[] args)
    {
        System.out.println(Math.ceil(23.46)); // Prints 24
        System.out.println(Math.floor(23.46)); // Prints 23
    }
}

我怀疑要么你没有得到你认为你拥有的输入数据,要么你没有写出你认为你是的输出数据。/自己工作正常。它们唯一会返回相同值的时间是当输入已经是整数时。你谈论解析你的双重...我的猜测是错误就在那里。请向我们展示一个简短但完整的程序,以演示问题。Math.floorceil

(在非常大的值周围可能存在其他情况,其中确切的目标整数不能完全表示为 - 我还没有检查过 - 但这里肯定不是这种情况。double


答案 2
float x = ((float)2346/100);  // You should type cast. Otherwise results 23
Math.ceil(x);                 // So Math.ceil(23) is 23 !!!
                              // Here I type cast to float.
                              // So I get the result 24