6

我正在尝试类的方法和功能,但NumberFormat我得到了一个奇怪的结果。我编译并运行以下程序:

public static void main(String[] args) {

Locale loc = Locale.US;
    NumberFormat nf = NumberFormat.getInstance(loc);
    System.out.println("Max: "+nf.getMaximumFractionDigits());
    System.out.println("Min: "+nf.getMinimumFractionDigits());
    try {
        Number d = nf.parse("4527.9997539");
        System.out.println(d);
        // nf.setMaximumFractionDigits(4);
        System.out.println(nf.format(4527.999753));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

输出是:

Max: 3
Min: 0
4527.9997539
4,528

这意味着它不考虑任何小数位数。如果我取消注释该行:

nf.setMaximumFractionDigits(4);

输出是:

Max: 3
Min: 0
4527.9997539
4,527.9998

换句话说,它工作正常。方法实际发生了什么setMaximumFractionDigits()并且在第一种情况下它没有带来包含 3 个小数位的数字?

4

3 回答 3

13

我终于找到了答案。方法setMaximumFractionDigits()只对方法有影响format()。它与 . 无关parse()。在我的代码片段中,我format()在手动将小数位数设置为 4 后使用该方法,因此它会影响结果。

于 2013-02-02T10:11:26.517 回答
3

如果要手动设置小数位数,请使用以下选项之一:

首先:

  //sets 'd' to 3 decimal places & then assigns it to 'formattedNum'
   String formattedNum = String.format("%.3f", d); //variable 'd' taken from your code above 

或者

  //declares an object of 'DecimalFormat'
   DecimalFormat aDF = new DecimalFormat("#.000"); 

  //formats value stored in 'd' to three decimal places
   String fomrattedNumber = aDF.format(d); 

在我看来,第二种选择最适合您的情况。

于 2013-01-10T19:38:40.233 回答
1

从解析的字符串创建的数字有更多的小数位数。但是当您尝试输出时,它使用格式MaximumFractionDigits从任何给定的数字创建字符串。

于 2013-01-10T17:58:31.813 回答