【发布时间】:2010-02-19 12:08:11
【问题描述】:
我有兴趣拥有以下getNumberOfDecimalPlace 功能:
System.out.println("0 = " + Utils.getNumberOfDecimalPlace(0)); // 0
System.out.println("1.0 = " + Utils.getNumberOfDecimalPlace(1.0)); // 0
System.out.println("1.01 = " + Utils.getNumberOfDecimalPlace(1.01)); // 2
System.out.println("1.012 = " + Utils.getNumberOfDecimalPlace(1.012)); // 3
System.out.println("0.01 = " + Utils.getNumberOfDecimalPlace(0.01)); // 2
System.out.println("0.012 = " + Utils.getNumberOfDecimalPlace(0.012)); // 3
我可以知道如何使用BigDecimal 来实现getNumberOfDecimalPlace 吗?
以下代码无法按预期工作:
public static int getNumberOfDecimalPlace(double value) {
final BigDecimal bigDecimal = new BigDecimal("" + value);
final String s = bigDecimal.toPlainString();
System.out.println(s);
final int index = s.indexOf('.');
if (index < 0) {
return 0;
}
return s.length() - 1 - index;
}
打印以下内容:
0.0
0 = 1
1.0
1.0 = 1
1.01
1.01 = 2
1.012
1.012 = 3
0.01
0.01 = 2
0.012
0.012 = 3
但是,对于案例 0、1.0,它并不能很好地工作。我期望结果是“0”。但结果却是“0.0”和“1.0”。这将返回“1”作为结果。
【问题讨论】:
-
您打算将输入参数设为 BigDecimal 还是仅在内部使用 BigDecimal?因为您的代码示例中的输入参数只是一个双精度参数。
-
我发现这里的解决方案对实现该功能很有用:stackoverflow.com/questions/6264576/…
-
这是哪个“Utils”?
标签: java