浮点数格式化

12

我有一个类型为double的变量,我需要将其打印出来并保留三位小数,但不能有任何尾随零...

例如,我需要:

2.5 // not 2.500
2   // not 2.000
1.375 // exactly till 3 decimals
2.12  // not 2.120

我尝试使用 DecimalFormatter,这样做有问题吗?

DecimalFormat myFormatter = new DecimalFormat("0.000");
myFormatter.setDecimalSeparatorAlwaysShown(false);

谢谢。:)

3个回答

22

尝试使用模式"0.###"而不是"0.000"

import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat("0.###");
        double[] tests = {2.50, 2.0, 1.3751212, 2.1200};
        for(double d : tests) {
            System.out.println(df.format(d));
        }
    }
}

输出:

2.5
2
1.375
2.12

6
您的解决方案几乎正确,但您应该将十进制格式模式中的零'0'替换为井号“#”。
因此,它应该看起来像这样:
DecimalFormat myFormatter = new DecimalFormat("#.###");

那行代码不是必需的(因为默认情况下 decimalSeparatorAlwaysShownfalse)。
myFormatter.setDecimalSeparatorAlwaysShown(false);

这是来自Javadocs的简短摘要:
Symbol  Location    Localized?  Meaning
0   Number  Yes Digit
#   Number  Yes Digit, zero shows as absent

这是一个Java API Decimal Format的链接:DecimalFormat

4
使用 NumberFormat 类。
示例:
    double d = 2.5;
    NumberFormat n = NumberFormat.getInstance();
    n.setMaximumFractionDigits(3);
    System.out.println(n.format(d));

输出结果将是2.5,而不是2.500。


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