Formatting a double and not rounding off

2020-02-13 07:38发布

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

5条回答
家丑人穷心不美
2楼-- · 2020-02-13 08:09

Why not use BigDecimal

BigDecimal a = new BigDecimal("10.126");
BigDecimal floored = a.setScale(2, BigDecimal.ROUND_DOWN);  //  == 10.12
查看更多
beautiful°
3楼-- · 2020-02-13 08:13

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.

查看更多
Fickle 薄情
4楼-- · 2020-02-13 08:29

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
查看更多
兄弟一词,经得起流年.
5楼-- · 2020-02-13 08:30

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

df.setRoundingMode(RoundingMode.DOWN);
查看更多
女痞
6楼-- · 2020-02-13 08:33

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));
查看更多
登录 后发表回答