java code round to two decimal place

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: http://salmanjamali.blogspot.my/2008/01/java-rounding-off-to-2-decimal-places.html
           :http://www.thescripts.com

Comments

Popular posts from this blog

Lab Network 2024

Step to publish your static html web page to GitHub

Tutorial OOP(reversion java)