看起来java的Math.round
函数有问题,当传递整数值给它时。我运行了几个输入,但给出了惊人的错误结果。
示例代码:
public static void main(String[] args) {
System.out.println("roundOff1: " + Math.round(1669053278));
System.out.println("roundOff2: " + Math.round(1669053304));
System.out.println("roundOff3: " + Math.round(1669053314));
System.out.println("roundOff4: " + Math.round(1669053339));
}
Stdout:
roundOff1: 1669053312
roundOff2: 1669053312
roundOff3: 1669053312
roundOff4: 1669053312
我的用例是四舍五入System.currentTimeMillis()/1000
,但最终得到错误的结果。我真的在Java中发现了一个bug或者遗漏了什么吗?
int值没有小数点,所以它们不能四舍五入,所以你需要添加一个额外的参数来四舍五入方法如要四舍五入到最接近的10,可以使用
Math. round(num/10.0) * 10;
public static void main(String[] args) {
System.out.println("roundOff1: " + Math.round(1669053278d));
System.out.println("roundOff2: " + Math.round(1669053304d));
System.out.println("roundOff3: " + Math.round(1669053314d));
System.out.println("roundOff4: " + Math.round(1669053339d));
}
您需要使用如上所示的double value。Math.round(double)返回long。但是Math.round(float)返回int。默认情况下,你的代码使用Math.round(float) &结果值超出整型范围。这就是问题所在
它在您的情况下不起作用的原因是,如果您的数据是小数,则舍入函数只能最优地工作!你的数值数据是整数(没有小数的数字)。结果,Math。圆函数不能工作!所以,用数学。正确的四舍五入函数,你必须有十进制数字作为你的数据。
为了说明这一点,我编写了代码并添加了小数,以向您展示Java上Math.round()的最佳输出:
import java.lang.Math;
class RoundingNumbers{
public static void main(String[] args){
double first_parameter = 1669053278.3;
System.out.println("roundOff1: " + Math.round(first_parameter));
double second_parameter = 1669053304.8;
System.out.println("roundOff2: " + Math.round(second_parameter));
double third_parameter = 1669053314.8;
System.out.println("roundOff3: " + Math.round(third_parameter));
double fourth_parameter = 1669053339.5;
System.out.println("roundOff4: " + Math.round(fourth_parameter));
}
尝试使用java.time.Instant
来完成系统时间的舍入,如下所示:
// the getEpochSecond() truncates - so add 500 millis first
long roundedSecs = Instant.now().plusMillis(500).getEpochSecond();
和一个演示程序:
// use a loop iterating every 250millis to demonstrate rounding
public static void main(String[] args) {
try {
for (int i = 0; i < 10; i++) {
Instant nowTime = Instant.now();
long b4 = nowTime.getEpochSecond();
nowTime = nowTime.plusMillis(500);
long result = nowTime.getEpochSecond();
System.out.println("b4: "+b4+" after:"+result);
Thread.sleep(250);
}
} catch (Exception e) {}
}
打印:
b4: 1669056744 after:1669056744
b4: 1669056744 after:1669056745
b4: 1669056745 after:1669056745
b4: 1669056745 after:1669056746
b4: 1669056745 after:1669056746
b4: 1669056746 after:1669056746
b4: 1669056746 after:1669056746
b4: 1669056746 after:1669056747
b4: 1669056746 after:1669056747
b4: 1669056747 after:1669056747