如何确定双精度数的小数位数?

How to determine number of decimals on a double?

这个问题已被多次问到,但我有一些规格在以前的问题中从未提到过。

我想知道小数点后有多少个数字,包括最后的零。

我试过这个:

double d= user_input;
String text =Double.toString(Math.abs(d));
int integerPlaces =text.indexOf('.');
int decimalPlaces =text.length() - integerPlaces - 1;

其中 user_input 是用户可以输入的任何值。

它运行良好,例如 2.384 显示 3 小数,这是正确的。

但是当用户输入:2.38400 它仍然显示忽略零的 3 小数。我还想计算这些零以获得结果 5.

我该如何解决这个问题?

试试这个

String text = YOUR_EDIT_TEXT.getText().toString().trim();


String[] arr = text.split("\.");

int noOfDecimalPlaces = arr[1].length();

希望这对您有所帮助。随时要求澄清...

 String text = "34.0003400";

 int noOfDecimalPlaces = text.length() - text.indexOf(".") - 1;

更新

String text = "3454";
        int noOfDecimalPlaces;
        if (text.indexOf(".") != -1) {
            noOfDecimalPlaces = text.length() - text.indexOf(".") - 1;
        } else {
            noOfDecimalPlaces = 0;
        }