2016-12-21 44 views
0

我想检查String是否包含Double而不是Integer。我正在这样工作;检查Java中的有效双精度

private boolean isDouble(String str) { 
     try { 
      Double.parseDouble(str); 
      return true; 
     } 
     catch(NumberFormatException e) { 
      return false; 
     } 

    } 

对于检查它,我只是通过;

isDouble("123"); 

但它不工作,在两个条件给予true( “123”, “123.99”)。这里有什么问题?

+2

从技术上讲,123也是双。 –

回答

3

如果要检查它是一个数字,不适合在整数,你可能会舍的两倍。例如。利用事实round(1.2) != 1.2,但round(1) == 1

private boolean isDouble(String str) { 
    try { 
     // check if it can be parsed as any double 
     double x = Double.parseDouble(str); 
     // check if the double can be converted without loss to an int 
     if (x == (int) x) 
      // if yes, this is an int, thus return false 
      return false; 
     // otherwise, this cannot be converted to an int (e.g. "1.2") 
     return true; 
     // short version: return x != (int) x; 
    } 
    catch(NumberFormatException e) { 
     return false; 
    } 

} 
+0

你能打破这种说法吗? 'return x!=(int)Math.round(x);'新手无法理解。 :) – user6750923

+0

'return E;'返回表达式* E *的值。在这种情况下,* E *是一个布尔条件'x!=(int)x'。实际上,这一轮可以被放弃。更新了我的答案。 –

0

您可以使用扫描仪(字符串)并使用hasNextDouble()方法。来自javadoc:

如果使用nextDouble()方法将此扫描器输入中的下一个标记解释为double值,则返回true。 例如:

if(source.contains(".")){ 
    Scanner scanner = new Scanner(source); 
    boolean isDouble = scanner.hasNextDouble(); 
    return isDouble; 
} 
return false; 
+0

补充条件 – NehaK

0

您也可以随时通过解析到double开始,然后测试,如果doubleint与否。

private void main() { 

    String str = "123"; 

    Double value = parseDouble(str); 
    boolean isInt = isInt(value); 
} 

private void isInt(Double value) { 
    if(value != null) { 
     return (value == (int) value) ? true : false; 
    } 
    return false; 
} 

private double parseToDouble(String str) { 
    Double value = null; 
    try { 
     value = Double.parseDouble(str); 
    } 
    catch(NumberFormatException e) { 
     // Do something 
    } 
    return value; 
} 
+0

为什么你不检查平等?这可以除以零。 –

+0

@MartinNyolt你是对的,我的坏。 – Aidin

0

这个问题是由于这样的事实:1.00为1,这是一个双。 这意味着您不能简单地解析double并假装代码检测到自身是否为int。为此,您应该添加一个检查,我认为最简单的是:

private boolean isDouble(String str) { 
    try { 
    double myDouble = Double.parseDouble(str); 
    myDouble -= (int)myDouble; //this way you are making the (for example) 10.3 = 0.3 

    return myDouble != (double)0.00; //this way you check if the result is not zero. if it's zero it was an integer, elseway it was a double 
    } 
    catch(NumberFormatException e) { 
    return false; 
    } 
} 

我做到了没有编辑,所以告诉我,如果事情是错的。

希望这有助于

0

检查简单的代码

private boolean isDecimalPresent(d){ 
try { 
    return d%1!=0; 
} 
catch(NumberFormatException e) { 
    return false; 
}