Validate a numberTag(s): String/Number


public class NumberUtils {

  private NumberUtils() {}

  // Check if given string is a number (digits only)
  public static boolean isNumber(String string) {
      return string.matches("^\\d+$");
  }

  // Check if given string is numeric (-+0..9(.)0...9)
  public static boolean isNumeric(String string) {
      return string.matches("^[-+]?\\d+(\\.\\d+)?$");
  }

  // Check if given string is number with dot separator and two decimals.
  public static boolean isNumberWith2Decimals(String string) {
    return string.matches("^\\d+\\.\\d{2}$");
  }

  public static void main(String[] args) {
    System.out.println("42 valid ? "   + NumberUtils.isNumber("42"));
    System.out.println("42.1 valid ? " + NumberUtils.isNumber("42.1"));

    System.out.println("42 valid ? "     + NumberUtils.isNumeric("42"));
    System.out.println("42.1 valid ? "   + NumberUtils.isNumeric("42.1"));
    System.out.println("-42.1 valid ? "  + NumberUtils.isNumeric("42.1"));
    System.out.println("-42.1a valid ? " + NumberUtils.isNumeric("42.1a"));

    System.out.println("42.10 valid ? "  + NumberUtils.isNumberWith2Decimals("42.10"));
    System.out.println("42.101 valid ? " + NumberUtils.isNumberWith2Decimals("42.101"));
    System.out.println("42,10 valid ? "  + NumberUtils.isNumberWith2Decimals("42,10"));
    System.out.println("42 valid ? "     + NumberUtils.isNumberWith2Decimals("42"));

    /*
     * output
     * 42.1 valid ? false
     * 42   valid ? true
     *
     * 42.1   valid ? true
     * -42.1  valid ? true
     * -42.1a valid ? false
     *
     * 42.10  valid ? true
     * 42.101 valid ? false
     * 42,10  valid ? false
     * 42     valid ? false
     */
  }
}

blog comments powered by Disqus