18

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

mskfisher
  • 3,291
  • 4
  • 35
  • 48
SMA_JAVA
  • 471
  • 4
  • 9
  • 18
  • This was asked the same week here https://stackoverflow.com/questions/8486878/how-to-cut-off-decimal-in-java-without-rounding -- this has lot more options – Asif Mohammed Feb 17 '17 at 23:03

5 Answers5

25

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
Bohemian
  • 412,405
  • 93
  • 575
  • 722
11

You can set the rounding mode of the formatter to DOWN:

df.setRoundingMode(RoundingMode.DOWN);
MByD
  • 135,866
  • 28
  • 264
  • 277
3

Why not use BigDecimal

BigDecimal a = new BigDecimal("10.126");
BigDecimal floored = a.setScale(2, BigDecimal.ROUND_DOWN);  //  == 10.12
Brad
  • 15,186
  • 11
  • 60
  • 74
0

Have you tried RoundingMode.FLOOR?

String s1 = "10.126";
Double f1 = Double.parseDouble(s1);
DecimalFormat df = new DecimalFormat(".00");
df.setRoundingMode(RoundingMode.FLOOR);

System.out.println("f1"+df.format(f1));
John B
  • 32,493
  • 6
  • 77
  • 98
0

If all you want to do is truncate a string at two decimal places, consider using just String functions as shown below:

String s1 = "10.1234";
String formatted = s1;
int numDecimalPlaces = 2;
int i = s1.indexOf('.');
if (i != -1 && s1.length() > i + numDecimalPlaces) {
    formatted = s1.substring(0, i + numDecimalPlaces + 1);
}
System.out.println("f1" + formatted);

This saves on parsing into a Double and then formatting back into a String.

dogbane
  • 266,786
  • 75
  • 396
  • 414
  • Thanks man....i can use it ...but then i wanted something more compact..and also i need to do a couple of calculations on these values, so any ways there will be some amount of parsing required – SMA_JAVA Dec 19 '11 at 12:01