2013-08-25 30 views
1

任何人都可以用简单的英语解释以下从API中取得的以下内容?FieldPosition使用NumberFormat格式化数字

您还可以使用的parse和format方法的形式与 一个ParsePosition和FieldPosition中,让您可以:

通过串

件逐步解析对齐小数点和其他领域

例如,您可以通过两种方式对齐数字: 如果您使用带间距的等宽字体进行对齐,则可以在格式调用中传递 FieldPosition,字段= INTEGER_FIELD。在输出时,getEndIndex将被设置为整数的最后一个字符与小数之间的偏移量 。在字符串的前面添加 (desiredSpaceCount - getEndIndex)空格。

我还没有得到什么是FieldPosition的使用和上面发布的API没有帮助(至少对我来说)。 一个简单的例子显示输出将是超级! 在此先感谢!

回答

1

的NumberFormat是所有数字格式的抽象基类。此类提供接口,用于格式化和解析号码。

要使用数字格式,首先必须获取区域设置实例

然后,您可以设置格式化的许多属性。就像,您可以选择显示逗号,限制小数位数,并设置最小和最大整数长度。如果你想显示区域设置的'%',那么你必须使用NumberFormat。不要将'%'作为字符串附加到结果中。你是否想显示像(3745)这样的paranthesis来代替“ - ”来表示负数,然后使用NumberFormat。像这样,有很多用途。

您可以检查JavaDoc更多的方法

这就告诉你该怎么办呢.. !!

NumberFormat numberFormat = NumberFormat.getInstance(); 

    // setting number of decimal places 
    numberFormat.setMinimumFractionDigits(2); 
    numberFormat.setMaximumFractionDigits(2); 

    // you can also define the length of integer 
    // that is the count of digits before the decimal point 
    numberFormat.setMinimumIntegerDigits(1); 
    numberFormat.setMaximumIntegerDigits(10); 

    // if you want the number format to have commas 
    // to separate the decimals the set as true 
    numberFormat.setGroupingUsed(true); 

    // convert from integer to String 
    String formattedNr = numberFormat.format(12345678L); 
    // note that the output will have 00 in decimal place 


    // convert from decimal to String 
    numberFormat.format(12345.671D); 

    // format a String to number 
    Number n1 = null; 
    Number n2 = null; 

     n1 = numberFormat.parse("1,234"); 
     n2 = numberFormat.parse("1.234"); 

    // show percentage 
    numberFormat = NumberFormat.getPercentInstance(); 
    numberFormat.format(0.98); 
    // answer will be 98% 

这是你如何使用与数字格式场位置

// Get a default NumberFormat instance. 
     NumberFormat numForm = NumberFormat.getInstance(); 

     // Format some decimals using the pattern supplied above. 
     StringBuffer dest1 = new StringBuffer(24); 
     StringBuffer dest2 = new StringBuffer(24); 
     FieldPosition pos = new FieldPosition(NumberFormat.FRACTION_FIELD); 

     dest1 = numForm.format(22.3423D, dest1, pos); 
     System.out.println("dest1 = " + dest1); 
     System.out.println("FRACTION is at: " + pos.getBeginIndex() + 
      ", " + pos.getEndIndex()); 

     dest2 = numForm.format(64000D, dest2, pos); 
     System.out.println("dest2 = " + dest2); 
     System.out.println("FRACTION is at: " + pos.getBeginIndex() + 
      ", " + pos.getEndIndex()); 
/* 
Output: 
dest1 = 22.342 
FRACTION is at: 3, 6 
dest2 = 64,000 
FRACTION is at: 6, 6 
*/ 
+0

你没有回答我的问题。 – Rollerball

+0

@Rollerball对不起,我迷路了;-)希望你明白:) – Dileep

2

FieldPositionParsePosition类的java文档给出了一些更多的提示。

基本上你可以使用FieldPosition,如果你不想格式化整个日期或数字,但只是其中的一部分(例如,如果你的用户界面将数量分成几个部分(如在两个输出字段中给出美元和美分) 。如果你需要类似的东西,你可以使用FieldPosition来检索你感兴趣的部分。 对于ParsePosition我现在没有一个好的用例在脑海中,也许别人可以在这里帮忙。