1

I am writing a program to get the average of two numbers. For test case, 2, 4 the output should be 3 not 3.0. For test case, -1282660896, -672813783 the output should be -977737339.5 not -9.777373395E8.

My code is like this:

public static void getAve(long a, long b){
     System.out.println((double)(a + b) / 2);
}

I also created a format function to meet my need, like this:

public static String fmt(double d) {
        if (d == (long) d)
            return String.format("%d", (long) d);
        else
            return String.format("%s", d);
    }

But this also fails for test case 2

Jainendra
  • 24,713
  • 30
  • 122
  • 169

2 Answers2

0

For your case, you can do String.format("%d", (int)d) but only in the case if d doesn't have a decimal part.

Actually there is already an answer for that:

How to nicely format floating numbers to String without unnecessary decimal 0?

Community
  • 1
  • 1
Ashalynd
  • 12,363
  • 2
  • 34
  • 37
0

For the case 2, you want to use a format that doesn't use scientific notation and specify the precision:

return String.format("%.1f", d);  // only one digit fractional precision

See http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

Also, comparing double to int is dangerous, since double is not guaranteed to represent exactly an integer. You'd better check if it close to an integer up to a predefined epsilon.

Cyrille Ka
  • 15,328
  • 5
  • 38
  • 58