How to remove the " .0" in a whole number when using double in java? [duplicate]
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 anyon开发者_运维知识库e help me how to remove that .0 in a whole number?
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);
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.
精彩评论