格式化浮点数

st0*_*0le 12 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
Run Code Online (Sandbox Code Playgroud)

我试过用DecimalFormatter,我做错了吗?

DecimalFormat myFormatter = new DecimalFormat("0.000");
myFormatter.setDecimalSeparatorAlwaysShown(false);
Run Code Online (Sandbox Code Playgroud)

谢谢.:)

Bar*_*ers 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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

2.5
2
1.375
2.12
Run Code Online (Sandbox Code Playgroud)


Mar*_*icz 6

你的解决方案几乎是正确的,但是你应该用十进制格式模式用"#"替换零'0'.

所以看起来应该是这样的:

DecimalFormat myFormatter = new DecimalFormat("#.###");
Run Code Online (Sandbox Code Playgroud)

而该行不necesary(如decimalSeparatorAlwaysShownfalse默认):

myFormatter.setDecimalSeparatorAlwaysShown(false);
Run Code Online (Sandbox Code Playgroud)

以下是javadocs的简短摘要:

Symbol  Location    Localized?  Meaning
0   Number  Yes Digit
#   Number  Yes Digit, zero shows as absent
Run Code Online (Sandbox Code Playgroud)

以及javadoc:DecimalFormat的链接