Java 设置double的格式而不是四舍五入

Java 设置double的格式而不是四舍五入,java,floating-point,double,Java,Floating Point,Double,我需要将双精度的格式(而不是四舍五入)设置为小数点后两位 我试过: String s1 = "10.126"; Double f1 = Double.parseDouble(s1); DecimalFormat df = new DecimalFormat(".00"); System.out.println("f1"+df.format(f1)); 结果: 10.13 但是我要求输出为10.12您试过了吗 您可以将格式化程序的舍入模式设置为“向下”: df.setRoundingMode(

我需要将
双精度
的格式(而不是四舍五入)设置为小数点后两位

我试过:

String s1 = "10.126";
Double f1 = Double.parseDouble(s1);
DecimalFormat df = new DecimalFormat(".00");
System.out.println("f1"+df.format(f1));
结果:

10.13
但是我要求输出为
10.12

您试过了吗


您可以将格式化程序的舍入模式设置为“向下”:

df.setRoundingMode(RoundingMode.DOWN);
调用以适当地设置:

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

如果你想做的是在两个小数点截断一个字符串,考虑只使用如下所示的字符串函数:

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);
这样可以将解析保存为双精度格式,然后将格式重新设置为字符串。

为什么不使用


你是说数学。圆(arg0)??实际上,这会将其舍入到最接近的整数。没有DecimalFormat的setRoundingMode谢谢你的建议..但我需要使用java 1.5..我想setRoundingMode()在1.6中可用查看我的答案使用BigDecimal代替是的,我使用的是当前版本-1.6。你也应该升级你的版本。谢谢老兄…我可以使用它…但是我想要更紧凑的东西…而且我需要对这些值做一些计算,所以任何方式都需要一些解析。这是在同一周提出的问题——这有更多的选择
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);
BigDecimal a = new BigDecimal("10.126");
BigDecimal floored = a.setScale(2, BigDecimal.ROUND_DOWN);  //  == 10.12