Java如何将格式转换为字符串。

3

我还是Java的新手,想知道有没有办法在不四舍五入的情况下格式化double? 例如:

double n = 0.12876543;
String s = String.format("%1$1.2f", n);

如果我打印到系统上,它会返回0.13而不是精确的0.12。现在,我已经想到了一个解决方案,但我想知道是否有更好的方法来解决这个问题。这是我的简单解决方案:

double n = 0.12876543;
double n =  Double.parseDouble(String.format(("%1$1.2f", n));

有其他的想法或解决方案吗?

3
请不要格式化到小数点后两位,这样它就不会被格式化为小数点后两位。当原始数字是 0.128... 时,0.120.13更精确吗? - Boris the Spider
使用 Math.floor()n = Math.floor(n * 100) / 100; - Phylogenesis
听起来你想在String.format中设置舍入模式,但是你不能这样做。也许可以使用BigDecimals代替?请参考https://dev59.com/ernqs4cB2Jgan1znJCtN的答案。 - BretC
或者您可以使用 String.format("%1$1.2f", n - 0.005); - Phylogenesis
这是针对法国用户的,他们使用逗号,这就是为什么我使用了能够识别你所使用机器的格式。这是一个支付系统,如果将所有数字加起来,其他数字都会产生差异,这就是为什么我不想将它们四舍五入。在这种情况下,我可以使用.replace(".", ",")来获取逗号。 - NewBie1234
4个回答

4
一种优雅的解决方案是使用DecimalFormatsetRoundingMode方法,它会适当设置RoundingMode
例如:
// Your decimal value
double n = 0.12876543;
// Decimal Formatting
DecimalFormat curDf = new DecimalFormat(".00");
// This will set the RoundingMode
curDf.setRoundingMode(RoundingMode.DOWN);
// Print statement
System.out.println(curDf.format(n));

输出:

0.12

另外,如果您想将字符串进行额外的格式化,您可以将双精度值转换为字符串:

// Your decimal value
double n = 0.12876543;
// Decimal Formatting
DecimalFormat curDf = new DecimalFormat(".00");
// This will set the RoundingMode
curDf.setRoundingMode(RoundingMode.DOWN);
// Convert to string for any additional formatting
String curString = String.valueOf(curDf.format(n));
// Print statement
System.out.println(curString);

输出:

0.12

请参考类似的解决方案: https://dev59.com/ZGoy5IYBdhLWcg3wa9ff#8560708

高人们想法相似。几乎和我的答案一样。 :) - Justin L
1
很高兴认识你,@Justin。 :D - PseudoAj
这很好,但我需要逗号的格式。该格式可以识别我正在使用的机器,并且可以识别是英语用户还是法语用户。我猜我可以使用.replace方法,但它需要一个字符串,这就是为什么我想到将string.format转换为double类型。我能得到带有舍入模式的逗号吗? - NewBie1234
@dtrembl5 我已根据您的需求更新了答案。 - PseudoAj
美妙!谢谢你,PseudoAj! - NewBie1234
@dtrembl5 没问题 :) - PseudoAj

2
今日免费次数已满, 请开通会员/明日再来
double n = 0.12876543;
String complete = String.valueOf(n);
System.out.println(complete);

DecimalFormat df = new DecimalFormat("#.##");
String rounded = df.format(n);
System.out.println(rounded);

df.setRoundingMode(RoundingMode.DOWN);
String truncated = df.format(n);
System.out.println(truncated);

它显示:

0.12876543
0.13
0.12

1
你的示例代码能够正确地将数字四舍五入到小数点后两位。例如,当数字0.12876543保留两位小数时,会被正确地四舍五入为0.13。但是,如果你总是想将数字向下取整呢?如果是这种情况,你可以尝试像这样做...
public static void main(String[] args) throws IOException, InterruptedException {
    double n = 0.12876543;

    DecimalFormat df = new DecimalFormat("#.##");
    df.setRoundingMode(RoundingMode.DOWN);
    String s = df.format(n);
    System.out.println(s);
}

这将打印出一个值为0.12。

0
请注意,双精度浮点数是二进制小数,实际上没有十进制位。
如果需要十进制位,请使用BigDecimal,它具有setScale()方法以进行截断,或者使用DecimalFormat以获取字符串。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接