Computer Science Canada

Rounding a Decimal to Two Decimal Places in Java

Author:  SS1389 [ Sat Nov 20, 2010 9:45 pm ]
Post subject:  Rounding a Decimal to Two Decimal Places in Java

Hey guys,

I was just wondering what's the easiest way to round a decimal to 2 decimal places in Java? Thanks.

Author:  andrew. [ Sat Nov 20, 2010 10:04 pm ]
Post subject:  RE:Rounding a Decimal to Two Decimal Places in Java

There may be a method for it, but you could just multiply by 100, round it, and then divide by 100.

e.g.
Java:
double result = 543.125;
result = Math.Round(result*100)/100;

Author:  SS1389 [ Thu Nov 25, 2010 10:17 pm ]
Post subject:  Re: Rounding a Decimal to Two Decimal Places in Java

Yup. That was the method I was looking for. Thanks!

Author:  unoho [ Thu Nov 25, 2010 11:04 pm ]
Post subject:  RE:Rounding a Decimal to Two Decimal Places in Java

i remember our prof made us do some DecimalFormat function..

Author:  eragon5000 [ Fri Nov 26, 2010 11:10 pm ]
Post subject:  Re: Rounding a Decimal to Two Decimal Places in Java

Yep Decimal Format is a lot easier to use:

code:
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(number));

Author:  SS1389 [ Thu Dec 09, 2010 5:37 pm ]
Post subject:  Re: Rounding a Decimal to Two Decimal Places in Java

I think the *100, Math.round(), then /100 is much easier. Thank you everyone for your responses.


: