Showing posts with label Number Format. Show all posts
Showing posts with label Number Format. Show all posts

Thursday, December 6, 2012

Java rounding off a float to two decimal places

double r = 5.1234;
System.out.println(r); // r is 5.1234

int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);

// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();

System.out.println(r); // r is 5.12
 

int n = 100; 
float f = (float) (Math.round(n*100.0f)/100.0f);

DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd2dec = new Double(df2.format(f)).doubleValue();

// The value of dd2dec will be 100.00 



int n = 100.203;
float f = (float) (Math.round(n*100.0f)/100.0f);

DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd2dec = new Double(df2.format(f)).doubleValue();

// The value of dd2dec will be 100.20