4

I like the suggestion in String to Int in java - Likely bad data, need to avoid exceptions to implement a utility method that parses an int, but returns a default value if the string cannot be parsed.

public static int parseInt(String s, int defaultValue) {
    if (s == null) return defaultValue;
    try {
         return Integer.parseInt(s);
     } catch (NumberFormatException x) {
         return defaultValue;
     }  
}

Is there an existing open source library (from apache commons, or google, for example) that implements this as well as for other data types such as boolean, float, double, long, etc?

Community
  • 1
  • 1
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109

2 Answers2

16

Apache Commons Lang has the class org.apache.commons.lang3.math.NumberUtils with convenient methods for convert. In another way, you can specify a default value if there is a error. e.g.

NumberUtils.toLong("")         => 0L
NumberUtils.toLong(null, 1L)   => 1L

NumberUtils.toByte(null)       => 0
NumberUtils.toByte("1", 0)     => 1
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
  • Although it does parse without exception, the default value might be undesirable. If that is your case like mine there is the org.apache.commons.validator.routines.LongValidator.validate(String) can also take a pattern and/or Locale. – Mashimom Feb 01 '21 at 14:18
7

Guava has several tryParse methods that return null on a failed parse, e.g. Ints.tryParse, Floats.tryParse, etc

Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
  • While these methods don't throw NumberFormatException, it should be noted that if you pass a null String into them, they will throw a NullPointerException rather than just returning null. – Stephen Ostermiller Apr 06 '16 at 09:35