格式化双,不舍入 [英] Formatting a double and not rounding off
本文介绍了格式化双,不舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将 double
格式化(和不)到2位小数。
I need to format (and not round off) a double
to 2 decimal places.
我尝试过:
String s1 = "10.126";
Double f1 = Double.parseDouble(s1);
DecimalFormat df = new DecimalFormat(".00");
System.out.println("f1"+df.format(f1));
结果:
10.13
但是我需要输出为$ code> 10.12
But I require the output to be 10.12
推荐答案
调用 setRoundingMode
设置 RoundingMode
适当地:
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));
输出
10.12
这篇关于格式化双,不舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文