代码之家  ›  专栏  ›  技术社区  ›  GingerHead

如何检查字符串是正数、负数还是非数字

  •  -2
  • GingerHead  · 技术社区  · 10 年前

    问题

    我有一个 String 我想知道 一串 是一个数字,也可以是负数

    测试用例

    String test1  = "abcd";     // Here it must show that it's not a number
    String test2  = "abcd-123"; // Here it must show that it's not a number
    String test3  = "123";      // Here it must show that it's a number
    String test4  = "-.12";     // Here it must show that it's a number
    String test5  = "-123";     // Here it must show that it's a number
    String test6  = "123.0;     // Here it must show that it's a number
    String test7  = "-123.00";  // Here it must show that it's a number
    String test8  = "-123.15";  // Here it must show that it's a number
    String test9  = "09";       // Here it must show that it's a number
    String test10 = "0.0";      // Here it must show that it's a number
    

    尝试过的东西

    我用过 StringUtils#isNumber NumberUtils#isNumber ,但他们无济于事, 负数 ,“09”显示为非数字

    4 回复  |  直到 6 年前
        1
  •  7
  •   kunpapa    10 年前

    您可以尝试以下操作:

    try {
        double value = Double.parseDouble(test1);
        if(value<0)
           System.out.println(value + " is negative");
        else
           System.out.println(value + " is possitive");
    } catch (NumberFormatException e) {
        System.out.println("String "+ test1 + "is not a number");
    }
    
        2
  •  3
  •   Andy Turner    10 年前

    根据Javadoc Double.valueOf :

    为了避免对无效字符串调用此方法并引发NumberFormatException,可以使用下面的正则表达式筛选输入字符串:

      final String Digits     = "(\\p{Digit}+)";
      final String HexDigits  = "(\\p{XDigit}+)";
      // an exponent is 'e' or 'E' followed by an optionally
      // signed decimal integer.
      final String Exp        = "[eE][+-]?"+Digits;
      final String fpRegex    =
          ("[\\x00-\\x20]*"+  // Optional leading "whitespace"
           "[+-]?(" + // Optional sign character
           "NaN|" +           // "NaN" string
           "Infinity|" +      // "Infinity" string
    
           // A decimal floating-point string representing a finite positive
           // number without a leading sign has at most five basic pieces:
           // Digits . Digits ExponentPart FloatTypeSuffix
           //
           // Since this method allows integer-only strings as input
           // in addition to strings of floating-point literals, the
           // two sub-patterns below are simplifications of the grammar
           // productions from section 3.10.2 of
           // The Java™ Language Specification.
    
           // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
           "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
    
           // . Digits ExponentPart_opt FloatTypeSuffix_opt
           "(\\.("+Digits+")("+Exp+")?)|"+
    
           // Hexadecimal strings
           "((" +
            // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
            "(0[xX]" + HexDigits + "(\\.)?)|" +
    
            // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
            "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
    
            ")[pP][+-]?" + Digits + "))" +
           "[fFdD]?))" +
           "[\\x00-\\x20]*");// Optional trailing "whitespace"
    
      if (Pattern.matches(fpRegex, myString))
          Double.valueOf(myString); // Will not throw NumberFormatException
      else {
          // Perform suitable alternative action
      }
    

    正则表达式内容丰富,但内容全面且有充分的文档记录。你可以随意修剪。

        3
  •  1
  •   Asendo    10 年前

    尝试将输入解析为一个整数,如果它不转换,则使用catch语句将其包围。如果它转换,则应返回一个字符,如果它返回一个数字

        4
  •  1
  •   Raju    10 年前
     public static String checknumeric(String str){
            String numericString = null;
            String temp;
          if(str.startsWith("-")){ //checks for negative values
              temp=str.substring(1);
              if(temp.matches("[+]?\\d*(\\.\\d+)?")){
                  numericString=str;
              }
          }
            if(str.matches("[+]?\\d*(\\.\\d+)?")) {
                numericString=str;
            }
            return numericString;
        }