格式化浮点数

问题描述:

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

I have a variable of type double, I need to print it in upto 3 decimals of precision but it shouldn't have any trailing zeros...

例如。我需要

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

我尝试使用 DecimalFormatter ,我做错了吗?

I tried using DecimalFormatter, Am i doing it wrong?

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

谢谢。 :)

尝试模式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