1

How can I display only 2 decimal places from the inputted answer? when I do this the answer is different

Scanner user_input = new Scanner(System.in);
float num;
DecimalFormat f = new DecimalFormat("##.00");
System.out.println("Enter any number");
num = user_input.nextFloat();
System.out.println("Square of "+num+" is: "+f.format(num)+Math.pow(num,2));
}

2 Answers2

0

You need to sum the power with the answer and then format the result. Currently you are formatting the number and afterwards performing the power function causing the result to be in raw format.

Modify your output line to:

System.out.println("Square of "+num+" is: "+f.format(num+Math.pow(num,2)));

So for an input of 21.12345 the result would look like:

Enter any number 21.12345 
Square of 21.12345 is: 467.32
pczeus
  • 7,709
  • 4
  • 36
  • 51
  • Your code was correct but let me fix some things. I think you don't need to put the identifier next to the Math.pow 'cuz the inputted number will add another to the result so the output will become 467.32 instead of 446.20 I hope you get it and sorry for my bad english! – cookieWarrior Aug 16 '16 at 01:55
0

System.out.printf works like C printf function. You can use it to format string with placeholders. It can also take care of formatting float values.

System.out.printf("Square of %.2f is: %.2f %n" , num, num * num);

Above code should take care of printing only 2 digits after decimal. %n is for new line.

For more information check this link https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

If you just need formatted String then you can use String.format method, which returns the formatted string filled with placeholder values.

11thdimension
  • 10,333
  • 4
  • 33
  • 71