[英]Two different outputs from Math.round(double * Math.pow(10, int))
[英]Cannot convert from long to int, why can't I round this double to the nearest int using Math.round
为什么我不能使用Math.round将此整数四舍五入到最接近的int,却收到此错误“无法从long转换为int”
Double bat_avg = Double.parseDouble(data[4])/Double.parseDouble(data[2]);
int ibat_avg = Math.round(bat_avg*1000.00);
System.out.println(bat_avg);
您可以改用float:
Float bat_avg = Float.parseFloat(data[4]) / Float.parseFloat(data[2]);
int ibat_avg = Math.round(bat_avg * 1000.00f);
System.out.println(bat_avg);
Math.round
有两个版本:
Math.round(double d)
返回long
。 int
Math.round(float)
。 Math.round(double)
将返回一个long,由于您将失去精度,因此不能隐式转换。 您必须将其显式转换为int:
int ibat_avg = (int)Math.round(bat_avg*1000.00);
Math.round(Double)返回一个long。 Math.round(float)返回一个int。
所以两个解决方案是
int ibat_avg = Math.round((float) bat_avg*1000.00);
要么
int ibat_avg = (int) Math.round(bat_avg*1000.00);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.