Cannot convert from long to int, why can't I round this double to the nearest int using Math.round

﹥>﹥吖頭↗ 提交于 2019-12-11 04:21:09

问题


why can't I round this double to the nearest int using Math.round, I get this error "cannot convert from long to 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);

回答1:


You can use float instead:

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);

There are two versions of Math.round:

  • Math.round(double d) which returns long.
  • Math.round(float) which returns int.



回答2:


Math.round(double) will return a long, which can't be implicitly casted as you would lose precision. You have to explicitly cast it to an int:

int ibat_avg = (int)Math.round(bat_avg*1000.00);



回答3:


Math.round(Double) returns a long. Math.round(float) returns an int.

So the two solutions are

int ibat_avg = Math.round((float) bat_avg*1000.00);

or

int ibat_avg = (int) Math.round(bat_avg*1000.00);


来源:https://stackoverflow.com/questions/16754634/cannot-convert-from-long-to-int-why-cant-i-round-this-double-to-the-nearest-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!