Validate a number

From CodeCodex

Implementations[edit]

Java[edit]

 public class 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   valid ? true
     * 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
     */
  }
}

Ruby[edit]

This operator (=~) returns an agreeing position or "nil". By the double negation, it returns a boolean value.

def number?(string)
  !!(string =~ /^\d+$/)  # !! is the double negation
end

def numeric?(string)
  !!(string =~ /^[-+]?\d+(\.\d+)?$/)
end

def number_with2decimals?(string)
  !!(string =~ /^\d+\.\d{2}$/)
end

format = "%-7svalid ? %s\n"
puts "number?"
["42", "42.1"].each do |string|
  printf format, string, number?(string)
end
puts "numeric?"
["42", "42.1", "-42.1", "-42.1a"].each do |string|
  printf format, string, numeric?(string)
end
puts "number_with2decimals?"
["42.10", "42.101", "42,10", "42"].each do |string|
  printf format, string, number_with2decimals?(string)
end

The execution result is same as Java.