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

21 java math

我有一个双(23.46)

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

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

Jon*_*eet 51

无法重现:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

(可能存在非常大的值的其他场景,其中精确的目标整数不能完全表示为double- 我没有检查 - 但这肯定不是这里的情况.)

  • "它们返回相同值的唯一时间是输入已经是整数"这最终成了我的问题.愚蠢的错误在我身边,谢谢你的帮助. (6认同)

Chr*_*s J 14

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
Run Code Online (Sandbox Code Playgroud)