如何找出小数的小数部分的长度或位数?
我可以看到一些方法,例如像这样的字符串:
public static int getNumberOfFractionDigits(Number number) {
Double fractionPart = number.doubleValue() - number.longValue();
return fractionPart.toString().length() - 2;
}
但是确定长度的最佳方法是什么?
如果我使用字符串,我可以想象一些问题,例如因为不同系统的区域设置和数字格式可能不同。有没有一个好的方法来计算它?也许没有迭代?
提前致谢。
最佳答案
我只是为此编写了一个简单的方法,希望它可以帮助别人。
public static int getFractionDigitsCount(double d) {
if (d >= 1) { //we only need the fraction digits
d = d - (long) d;
}
if (d == 0) { //nothing to count
return 0;
}
d *= 10; //shifts 1 digit to left
int count = 1;
while (d - (long) d != 0) { //keeps shifting until there are no more fractions
d *= 10;
count++;
}
return count;
}
关于java - 如何获取数字小数部分的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5314954/