2010-06-08 65 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