JAVA 四舍五入到最接近的数字

JAVA Round to closest number

如何将小数舍入到最接近的 "whole" 数字?

一行回答!

 public static long roundToClosestLong(long num, long div) {
         return (long) num / div + ((double) (num % div) / div < 0.5 ? 0 : 1);
 }

您可以尝试使用

float x = (float)Math.ceil(x); 

float y = (float)Math.round(y);

另请注意,我已将它们转换回浮点数,因为在将双精度数转换为浮点数时可能会丢失精度。

您可以使用 java.lang.Math class。

  1. Math#round(double) 将接受 double 作为参数并且 returns long
  2. Math#round(float) 将接受 float 作为参数并且 returns int

你可以这样做:

int result = (int) (yourValue + 0.5);

如果您只需要简单的舍入,这可能是比 Math.round(yourValue)

更高效的解决方案