We would like to know how to check if a string represent a float number.
public class Main { /*from w w w .ja va 2s . c om*/ public static void main(String[] args) { System.out.println(testNumber("2.2")); } public static Float testNumber(String aArg) { while (true) { if (aArg.length() == 0) { return null; } if (aArg.matches("-?\\d+(\\.\\d+)?") == true) { break; } else { throw new IllegalArgumentException("not a number"); } } return Float.parseFloat(aArg); } }
The code above generates the following result.