格式化浮点数

时间:2011-01-19 08:17:29

标签: java string floating-point double string-formatting

我有一个类型为double的变量,我需要以高达3位小数的精度打印它,但它不应该有任何尾随零...

例如。我需要

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

指向javadoc的链接:DecimalFormat

答案 2 :(得分:4)

使用NumberFormat类。

示例:

    double d = 2.5;
    NumberFormat n = NumberFormat.getInstance();
    n.setMaximumFractionDigits(3);
    System.out.println(n.format(d));

输出为2.5,而不是2.500。

相关问题