Wednesday, January 23, 2008

Java: Rounding off to 2 decimal places

Seeking the simplest way to round off a float value to 2 decimal places, i found these:

Method 1:
x = (double)int((x+0.005)*100.0)/100.0;

Method 2:
x = Math.round(x*100.0) / 100.0;

Method 3:
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();

Method 4:
f = (float) (Math.round(n*100.0f)/100.0f);

Method 5:
double r = 5.1234;
System.out.println(r); // r is 5.1234
int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP); // setScale is immutable
r = bd.doubleValue();
System.out.println(r); // r is 5.12

[source: www.thescripts.com, accuracy unchecked]

How I did it:
float percentage = score.floatValue()/(qapairs.length*10)*100; //my float value
percentage = Float.valueOf((new DecimalFormat("###.00").format(percentage)));

15 comments:

Anonymous said...

thanks! this post is helpful!

Anonymous said...

Hi
This post was very helpful - I used method 4 in one of my dashboard reports in excel and works like a charm.

Thanks
Yudesh

Anonymous said...

Thanks for the post. I found it useful!

Anonymous said...

WOW!!!!!!!!!
NUMBER 2 IS FANTASTIC,WORKED LIKE A....AH..anyway it worked!!
THANKS.

abdul basith m said...

to round string value
"479.357" to "479.36"

Anonymous said...

thx bro helped a lot =D

dunno how you did method 2, plz send me explanation if you can and if you're still around:

aamir_raza60@hotmail.com

Thanks!

Anonymous said...

Hi, Good very Good!
Number two is fantastic..
Congratatulations.

Faraz said...

Hey Salman!
This is a very useful post. Good job.

Unknown said...

i came to know new thing today it helped me alot.

Brent Porter said...

I use a version like #3 - this is a good format because it is very intuitive if you wish to vary the number of significant digits(decimal places) by just extended the decimal format string pattern. My version is close to Salman's but I have a different format implementation. Instead of the new Double etc. etc
Double numberFormatted = Double.parseDouble(df2.format(numberToBeRounded))
Thanks,
BP

Anonymous said...

Thanks, it was very useful.

Anonymous said...

Thanks, that cut the mustard for me!
Seriously, your solutions are miles ahead of everything else I've seen on the web.
Keep it up Salman!!

Miguel Perez said...

I used method 4, it worked a treat. Thank you.

It's amazing how users like can find this article incredibly useful 4 years after you wrote it. Keep up the good article writing.

Sohil said...

Thanks brother. Tried Method 5. Worked Wonders. :)

Anonymous said...

A Real help. Thanks :D