如何通过向下舍入来将一个double转换为Java中的一个int?
问题描述:
我需要在Java中将double转换为int,但数值必须总是向下舍入。即99.99999999 - > 99
I need to cast a double to an int in Java, but the numerical value must always round down. i.e. 99.99999999 -> 99
答
强制转换为int会隐式删除任何小数。无需调用Math.floor()(假设为正数)
Casting to an int implicitly drops any decimal. No need to call Math.floor() (assuming positive numbers)
只需使用(int)类型转换,例如:
Simply typecast with (int), e.g.:
System.out.println((int)(99.9999)); // Prints 99
这就是说,它与 Math.floor
向负无穷大(@Chris Wong)舍入
This being said, it does have a different behavior from Math.floor
which rounds towards negative infinity (@Chris Wong)