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

huangapple go评论72阅读模式
英文:

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

我该如何修复这个问题呢?

英文:

This question has been asked severally but I have specifications that have never been mentioned in previously asked questions.

I want to know how many numbers are there after a decimal place including the last ZEROs.

I have tried this:

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

Where user_input is any value a user can put.

It is working well for example 2.384 is showing 3 decimals, that's correct.

But when the user puts: 2.38400 it is still showing 3 decimals ignoring the zeros. I want to also count those zeros to get the result as 5.

How can I fix this?

答案1

得分: 0

请尝试这样做:

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

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

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

希望对您有所帮助。如有需要,请随时询问以便澄清...

英文:

Try this

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


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

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

Hope this helps. Feel free to ask for clarifications...

答案2

得分: 0

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

## update

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

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

update

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

huangapple
  • 本文由 发表于 2020年7月27日 16:28:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63111432.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定