Cannot convert from long to int, why can't I r

2019-07-27 02:40发布

问题:

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