1

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);
user1750156
  • 35
  • 1
  • 5
  • 2
    [`Math.round` returns a `long`.](http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#round(double)) – Ry- May 25 '13 at 22:53
  • You need to cast it into an int. (int) Math.round(...) – greedybuddha May 25 '13 at 22:54
  • Yes, you can cast it to int, but you have to take into account this http://stackoverflow.com/questions/4355303/how-can-i-convert-a-long-to-int-in-java. – Lucia Pasarin May 25 '13 at 22:57

3 Answers3

3

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.
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • It's better to use `round` on an argument of type `double` and convert the result to `int` than to use `float` to the conversion unless the best representation of the value to be converted is a `float`. Given `float f=1234567.875f;`, the value of `round(f*1000.0f)` will be 1234567936. The original value was precisely representable, and the arithmetically-correct result of 1234567875 would be representable as `int`, but the result won't be a different value. Multiplying by 1000.0 would fix that. – supercat May 07 '15 at 20:39
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);
Supericy
  • 5,866
  • 1
  • 21
  • 25
1

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);
greedybuddha
  • 7,488
  • 3
  • 36
  • 50