Formatting a double and not rounding off

可紊 提交于 2019-12-08 22:29: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


回答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.



来源:https://stackoverflow.com/questions/8560632/formatting-a-double-and-not-rounding-off

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!