例如,当我使用Double.parseDouble()将字符串“ 12345678901234567890”解析为双精度时,它将返回值“ 12345678901234567000”,因为它最多可以容纳17位数字。
我想验证这种情况,并且应该只允许用户传递17位数字。我该怎么做?
示例: 1.2345678901234567890无效,因为其总数超过17位 1.2345E + 10有效
答案 0 :(得分:0)
尝试了类似的方法,可以使用拆分功能对数字进行计数
String input="12345678901234567E100";
String inputWithoutSign;
int lengthFullNumber;
int lengthFraction;
double v = Double.parseDouble(input);
if(input.startsWith("+") || input.startsWith("-")){
inputWithoutSign = input.split("[-+]",2)[1];
}
else inputWithoutSign = input;
String num = inputWithoutSign.split("[eE]", 2)[0];
if(num.indexOf('.') == -1){
lengthFullNumber = num.length();
lengthFraction = 0;
}else{
String[] splitNum = num.split("\\.", 2);
lengthFullNumber = splitNum[0].length();
lengthFraction = splitNum[1].length();
}
System.out.println("length:"+(lengthFullNumber+lengthFraction));
答案 1 :(得分:0)
假设我了解您限制数字位数的目标,那么这可能有助于解决问题。
测试用例
String[] vals = {
"12345678901234567890", "123456789091919191919",
"182828282.18282828", "182828282.182828282", "191929e10",
"192929.22929e10"
};
尝试解析它们
for (String v : vals) {
// remove possible decimal point and signs
String test = v.replaceAll("[.+-]", "");
// remove any exponents at end of string
test = test.replace("\\D+.*", "");
if (test.length() > 17) {
System.out.println(v + " has too many digits");
continue;
}
double d = Double.parseDouble(v);
System.out.println(v + " parses to " + d);
}