2014-10-17 66 views
4

试图找出为什么下面的代码不输出期望的结果。请指教。谢谢。NumberFormat:setMaximumFractionDigits - 未给出预期结果

import java.text.*; 

public class Test { 
    public static void main(String[] args) { 
     String s = "987.123456"; 
     double d = 987.123456d; 
     NumberFormat nf = NumberFormat.getInstance(); 
     nf.setMaximumFractionDigits(5); 
     System.out.println(nf.format(d) + " "); 
     try { 
      System.out.println(nf.parse(s)); 
     } catch (Exception e) { 
      System.out.println("got exc"); 
     } 
    } 
} 

输出:

987.12346 // Expected 987.12345 not 987.12346 
987.123456 
+0

为什么你想到了吗? – 2014-10-17 01:11:41

+0

'NumberFormat'正在四舍五入。请参阅http://stackoverflow.com/questions/3833137/how-to-make-number-format-not-to-round-numbers-up – Denise 2014-10-17 01:13:44

+0

Sotiri,我期待这是因为,我是在假设,因为我设置最大分数数字为5,对象应该返回5个不变的数字,但不知道舍入正在发生。 – 2014-10-17 15:11:03

回答

2

你的第二个打印不格式化double你解析。

// System.out.println(nf.parse(s)); 
System.out.println(nf.format(nf.parse(s))); // <-- 987.12346 

为了得到你要的输出,你可以添加一个调用NumberFormat#setRoundingMode(RoundingMode) - 像

nf.setMaximumFractionDigits(5); 
nf.setRoundingMode(RoundingMode.DOWN);