2010-06-08 61 views
3

當數字爲零(0)時是否可以顯示空白(空字符串)? (嚴格的左邊沒有零點)java.text.DecimalFormat在零時爲空?

+0

採用哪種方法?在DecimalFormat中有很多格式化字符串的方法 – TheLQ 2010-06-08 23:10:53

+0

數字是任何'java.lang.Number'還是一個特定的子類? – trashgod 2010-06-09 02:34:53

+0

@ Lord.Quackstar任何方法,讓我知道,如果任何方法會做。 @trashgod它是一個java.lang.Number,但如果它解決了我的問題,我可以使用特定的子類。 – Eduardo 2010-06-09 06:32:33

回答

5

您可以使用MessageFormat,特別是其ChoiceFormat特點:

double[] nums = { 
    -876.123, -0.1, 0, +.5, 100, 123.45678, 
}; 
for (double num : nums) { 
    System.out.println(
     num + " " + 
     MessageFormat.format(
      "{0,choice,-1#negative|0#zero|0<{0,number,'#,#0.000'}}", num 
     ) 
    ); 
} 

此打印:

-876.123 negative 
-0.1 negative 
0.0 zero 
0.5 0.500 
100.0 1,00.000 
123.45678 1,23.457 

注意MessageFormat不使用DecimalFormat下引擎蓋。從the documentation

FORMAT TYPE:  number 
FORMAT STYLE:  subformatPattern 
SUBFORMAT CREATED: new DecimalFormat(
         subformatPattern, 
         DecimalFormatSymbols.getInstance(getLocale()) 
        ) 

所以這使用DecimalFormat,儘管是間接的。如果由於某種原因而被禁止,那麼您必須自己檢查一下特殊情況,因爲DecimalFormat不能區分零。從the documentation

DecimalFormat模式的語法如下:

Pattern: 
     PositivePattern 
     PositivePattern ; NegativePattern 

沒有選項以零提供一個特殊的模式,所以沒有DecimalFormat模式,可以爲你做這個。如上所示,您可以擁有if,或者讓MessageFormat/ChoiceFormat爲您做。

+0

我真的需要使用java.text.DecimalFormat – Eduardo 2010-06-09 06:41:54

0

可以使用的String.format方法:

int num1=0; 
int num2=33; 
string str1 = (num1!=0) ? String.format("%3d", num1) : " "; 
string str2 = (num2!=0) ? String.format("%3d", num2) : " "; 

System.out.println("("+str1+")"); // output: ( ) 
System.out.println("("+str2+")"); // output: (33) 

格式的語法非常類似於C的printf(這個基本的使用)

+1

Er,它會將0打印爲「0」,而不是空字符串。 – 2012-10-02 17:29:23

+0

你是對的,這個答案是針對不同的問題... 我會做一些改變,以適應這一個以及:) – 2012-10-05 20:10:39