Thursday, 22 September 2011

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)));

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete