Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a double and not rounding off

I need to format (and not round off) a double to 2 decimal places.

I tried with:

String s1 = "10.126";
Double f1 = Double.parseDouble(s1);
DecimalFormat df = new DecimalFormat(".00");
System.out.println("f1"+df.format(f1));

Result:

10.13

But I require the output to be 10.12

like image 254
SMA_JAVA Avatar asked Dec 19 '11 11:12

SMA_JAVA


1 Answers

Call setRoundingMode to set the RoundingMode appropriately:

String s1 = "10.126";
Double f1 = Double.parseDouble(s1);
DecimalFormat df = new DecimalFormat(".00");
df.setRoundingMode(RoundingMode.DOWN); // Note this extra step
System.out.println(df.format(f1));

Output

10.12
like image 84
Bohemian Avatar answered Sep 30 '22 06:09

Bohemian