0

I am trying to round 16.275 to 2 decimal places in Java using Math.round(). It should be 16.28, but it keeps printing 16.27.

double x = 16.275; 
x = Math.round(x*100.0)/100.0;
System.out.println(x);

Could someone explain what I need to change to get 16.28? Thank you!

Emm
  • 11
  • 1
  • 2
    162.75 * 100.0 will give you 1627.49999999 (see the duplicate answer). – Mureinik Mar 14 '23 at 15:39
  • `System.out.printf("%.2f%n", 16.275);` – Unmitigated Mar 14 '23 at 15:47
  • @Mureinik This is not a duplicate and that not reply the question about rounding. To me, the question is about scientific rounding and HALF_EVEN method. – bugsbuRny Mar 14 '23 at 15:48
  • If you want accuracy rather than speed, use `BigDecimal` class. – Basil Bourque Mar 14 '23 at 15:49
  • 1
    @bugsbuRny If you don't let Java calculate 16.275 * 100.0 but instead use `Math.round(1627.5)/100.0`, you'll get the expected 16.28. The issue here is with the multiplication, not rounding. – Mureinik Mar 14 '23 at 15:51
  • But it does not help the asker. You are hard-coding the number in the formula. – bugsbuRny Mar 14 '23 at 16:03
  • @Emm Try this BigDecimal bigd = new BigDecimal(16.27515, MathContext.DECIMAL32); System.out.println(bigd.setScale(2, RoundingMode.HALF_EVEN ).doubleValue()); Changing the RoundingMode will give you the liberty to decide about the rounding type. – bugsbuRny Mar 14 '23 at 16:04

0 Answers0