25

Possible Duplicate:
How do I format a number in java?

I have problems in using Double. When the result is a whole number, it would display with a " .0" like 1.0, 2.0.

Can anyone help me how to remove that .0 in a whole number?

Community
  • 1
  • 1
ikzton
  • 273
  • 1
  • 3
  • 6
  • 1
    Closing of this question is not right as it is not a generic "How to format a number in Java" question, but rather a question on specific style of formatting. – MarianP Oct 06 '11 at 18:57
  • 1
    It should rather be a duplicate of http://stackoverflow.com/questions/703396/how-to-nicely-format-floating-types-to-string – rds Oct 21 '13 at 13:43

3 Answers3

62
import java.text.DecimalFormat;


public class Asdf {

    public static void main(String[] args) {
        DecimalFormat format = new DecimalFormat();
        format.setDecimalSeparatorAlwaysShown(false);

        Double asdf = 2.0;
        Double asdf2 = 2.11;
        Double asdf3 = 2000.11;
        System.out.println( format.format(asdf) );
        System.out.println( format.format(asdf2) );
        System.out.println( format.format(asdf3) );
    }

}

prints:

2
2.11
2,000.11

Using

DecimalFormat format=new DecimalFormat("#.#"); //not okay!!!

is not right as it messes with 10^3, 10^6, etc. separators.

2000.11 would be displayed as "2000.11" instead of "2,000.11"

This is of course if you want to display numbers properly formatted, not just using improper toString().

Also note, that formatting may different based on users Locale and DecimalFormat should be initialized accordingly using a factory method with user's Locale as an argument:

NumberFormat f = NumberFormat.getInstance(loc);
 if (f instanceof DecimalFormat) {
     ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
 }

http://download.oracle.com/javase/1.5.0/docs/api/java/text/DecimalFormat.html

UPDATE This formatting string works fine also without calling the extra method:

    DecimalFormat format=new DecimalFormat("#,###.#");
   //format.setDecimalSeparatorAlwaysShown(false);
CoolBeans
  • 20,654
  • 10
  • 86
  • 101
MarianP
  • 2,719
  • 18
  • 17
30

You need to use DecimalFormat to format your double.

public static void main(String[] args) {
      DecimalFormat decimalFormat=new DecimalFormat("#.#");
      System.out.println(decimalFormat.format(2.0)); //prints 2
}
CoolBeans
  • 20,654
  • 10
  • 86
  • 101
3

Format the string that you are displaying.

mbeckish
  • 10,485
  • 5
  • 30
  • 55