Java: I want to get an Integer output in double datatype

125 views Asked by At
class simple {
    public static void main() {
        double n, m;
        Scanner ip = new Scanner(System.in);
        n = ip.nextDouble();
        m = ip.nextDouble();
        m = n * m;
        System.out.println("Value in " + m);
    }
}

In the above code.. My output should only use decimal poinf if my input is using decimal point, rest of the time it should print like an integer.

Ex : INPUT : 2 , 3 --> OUTPUT : Value is 6

INPUT : 2.1, 1 --> OUTPUT : Value is 2.1

So my question is.... How can i print my number (with decimal point, without decimal point) according to my input?

3

There are 3 answers

0
Glorfindel On BEST ANSWER

You can use NumberFormat; the #-sign mean that decimals are only shown if they're non-zero.

System.out.println("Value in " + new DecimalFormat("0.########").format(m));
2
JP Moresmau On
0
Harish S On
    double n1,n2,n3,checkdecimal;
    n3=n1*n2;
    checkdecimal = n3 - Math.floor(n3);
    if(checkdecimal == 0)
    screen.setText(new DecimalFormat("0.#").format(this.Answer) + ""); // It will print without decimal point
    else
    screen.setText(this.Answer +""); // It will print with decimal point

Finally i found the solution myself ...