开发者

Formatting Floating Point Numbers

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...

eg. I need

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

I tried using DecimalFormatter, Am i doing it wrong?

DecimalF开发者_JS百科ormat myFormatter = new DecimalFormat("0.000");
myFormatter.setDecimalSeparatorAlwaysShown(false);

Thanks. :)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜