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?
s
? – Unitary0050
. Furthermore, what about leading spaces or anything like that? – Baerl0050
should be caught – ChaplinparseInt
issue in Java where the other one is a different issue, and it's in Javascript... (so the duplicate reported is incorrect.) – Baerl