1

I have a simple code:

int num1 = <user input>;
int num2 = <user input>;
String operation = <user input>;
double result = num1 operation num2;

Is there a way to format my output such that it will only display the decimal values if they are non-zero?

i.e.
5/3 = 3.67
5+3 = 8
Whooper
  • 575
  • 4
  • 20

1 Answers1

1

Try this way and see the results :

Scanner in = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("##.####");
double num = in.nextDouble();
String result = df.format(num);
System.out.println(result);

Output:

3.67
3.67
BUILD SUCCESSFUL (total time: 5 seconds)

8
8
BUILD SUCCESSFUL (total time: 2 seconds)

Update:

you can try this program that work for your requirements:

            Scanner in = new Scanner(System.in);
            DecimalFormat df = new DecimalFormat("##.####");
            double result = 0;
            int num1 = in.nextInt();
            int num2 = in.nextInt();
            String operation = in.next();

            if(operation.equals("/")){
                result = (double)num1 / num2;
            }
            else if(operation.equals("*")){
                result = num1 * num2;
            }
            else if(operation.equals("+")){
                result = num1 + num2;
            }
            else if(operation.equals("-")) {
                result = num1 - num2;
            }
            System.out.println(df.format(result));   

test case:

5
3
/
1.6667
BUILD SUCCESSFUL (total time: 3 seconds)
Oghli
  • 2,200
  • 1
  • 15
  • 37