Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

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

Thanks. :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
248 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...