Formatting Floating Point Numbers

杀马特。学长 韩版系。学妹 提交于 2019-11-29 06:12:31

Try the pattern "0.###" instead of "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));
        }
    }
}

output:

2.5
2
1.375
2.12

Your solution is almost correct, but you should replace zeros '0' in decimal format pattern by hashes "#".

So it should look like this:

DecimalFormat myFormatter = new DecimalFormat("#.###");

And that line is not necesary (as decimalSeparatorAlwaysShown is false by default):

myFormatter.setDecimalSeparatorAlwaysShown(false);

Here is short summary from javadocs:

Symbol  Location    Localized?  Meaning
0   Number  Yes Digit
#   Number  Yes Digit, zero shows as absent

And the link to javadoc: DecimalFormat

Use NumberFormat class.

Example:

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

Output will be 2.5, not 2.500.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!