Java ParseInt() - Catching Strings with a leading zero

s-low picture s-low · Feb 5, 2015 · Viewed 19.1k times · Source

Java's ParseInt method will happily parse decimal values supplied with a leading zero without throwing an exception, stripping the zero:

int value = Integer.parseInt("050", 10);

will result in the integer value 50.

But, I have an application requiring a string such as this to be rejected as invalid input. My solution to the problem so far has been to convert the parsed integer back to a string, and compare the lengths of original/parsed strings to see if any character has been stripped, eg:

String original = "050";
value  = Integer.parseInt( "050", 10);
String parsed = Integer.toString(value);
if (original.length() != parsed.length()) {
    System.exit(1);
}

Which works fine, but feels a little hacky. Are there better ways of detecting and handling a leading zero?

Answer

Eran picture Eran · Feb 5, 2015

Check if the first character is 0 :

if (original.charAt(0)=='0')

or

if (original.startsWith("0"))

If the String starts with a 0, you don't want to call parseInt at all.

I think that comparing a single character is more efficient than using regular expressions.