-2

I'm trying to reduce my decimal places down to only 2 but can't seem to find out how.This is a picture of what I have. Everything is done other than the decimal places. Any help is greatly appreciated.

Zach
  • 1
  • 2
    Paste your code, no images of it. Also the image did not any any attempt to format the numbers – azro Dec 02 '20 at 18:34

2 Answers2

0

Hey in one line : System.out.printf("%.2f", val);

In detail: Well actually this question is very similar too Here %.2f says that you want to float up to 2 points.

If you want to print till 3 decimal you can say %.3f and so on.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Krish Yadav
  • 165
  • 11
-1

I don't know if this is what you're asking for but a good way to get a float/double down to two decimal places is to multiply it by 100, round it, then divide by 100.

Danyman
  • 63
  • 1
  • 9
  • I have tried this and it didn't work thank though! – Zach Dec 02 '20 at 18:37
  • This *can* work, but floating-point round off makes it unreliable, so you might get lots of repeating 9s or repeating 0s followed by a 1. – kshetline Dec 02 '20 at 18:37
  • Personally this has always worked for me. I don't know how you guys are doing. If you have decimal D then you can just do Math.round(D*100)/100. If you want to round it another way just use Math.floor or Math.ceil – Danyman Dec 02 '20 at 18:39