Formatting Floating Point Numbers

18,277

Solution 1

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

Solution 2

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

Solution 3

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.

Share:
18,277

Related videos on Youtube

st0le
Author by

st0le

I solve stuff.

Updated on May 16, 2022

Comments

  • st0le
    st0le almost 2 years

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