How to remove the " .0" in a whole number when using double in java? [duplicate] How to remove the " .0" in a whole number when using double in java? [duplicate] android android

How to remove the " .0" in a whole number when using double in java? [duplicate]


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:

22.112,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

UPDATEThis formatting string works fine also without calling the extra method:

    DecimalFormat format=new DecimalFormat("#,###.#");   //format.setDecimalSeparatorAlwaysShown(false);


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}


Format the string that you are displaying.