天天看点

java判断小数位数_java-使用BigDecimal确定小数位数

我对具有以下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”.