6
(Math.round(doubleValue*100))/100.0

Is there a better way to round decimals to 2 decimal places?

Michael
  • 13,838
  • 18
  • 52
  • 81

2 Answers2

7

If you're interested in decimal places and therefore precise decimal values, you should typically be using java.math.BigDecimal to start with. You can then use Decimal.round or Decimal.setScale to round according to your exact needs.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3
DecimalFormat format=new DecimalFormat("#.##");
System.out.println(format.format(doubleValue));
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • 1
    You don't need to import anything from `java.lang`. – Martijn Courteaux Jun 27 '11 at 15:12
  • Do note: this does not round numbers. It just displays strings that have been formatted to a certain precision. The answer from John Skeet is the appropriate way to round to an explicit number of decimals without the juggling act of multiply-round-divide by OP. – Atreys Jun 27 '11 at 17:05