简体   繁体   中英

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

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

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM