Formatting a double and not rounding off

2020-02-13 08:20发布

问题:

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

回答1:

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


回答2:

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

df.setRoundingMode(RoundingMode.DOWN);


回答3:

Why not use BigDecimal

BigDecimal a = new BigDecimal("10.126");
BigDecimal floored = a.setScale(2, BigDecimal.ROUND_DOWN);  //  == 10.12


回答4:

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


回答5:

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.