Code Pretty Print Script

Tuesday, November 19, 2013

Converting Strings to Wrapper Types

Are you dealing with a lot of numeric data stored in strings? Don't you wish there were some simple utility wrappers to use? Try these:
  /**
   * Attempt to convert a String to a Float.
   * 
   * @param in
   *          The String to convert.
   * @return The Float value of the String, or Null.
   */
  public static Float toFloat(final String in) {
    if (in != null) {
      try {
        return Float.valueOf(in.trim());
      } catch (NumberFormatException e) {
      }
    }
    return null;
  }

  /**
   * Attempt to convert a String to a Double.
   * 
   * @param in
   *          The String to convert.
   * @return The Double value of the String, or Null.
   */
  public static Double toDouble(final String in) {
    if (in != null) {
      try {
        return Double.valueOf(in.trim());
      } catch (NumberFormatException e) {
      }
    }
    return null;
  }

  /**
   * Attempt to convert a String to an Integer in decimal.
   * 
   * @param in
   *          The String to convert.
   * @return The Integer value of the String, or Null.
   */
  public static Integer toInteger(final String in) {
    return toInteger(in, 10);
  }

  /**
   * Attempt to convert a String to an Integer.
   * 
   * @param in
   *          The String to convert.
   * @param radix
   *          The numeric base of the the String.
   * @return The Integer value of the String, or Null.
   */
  public static Integer toInteger(final String in,
      final int radix) {
    if (in != null) {
      try {
        return Integer.valueOf(in.trim(), radix);
      } catch (NumberFormatException e) {
      }
    }
    return null;
  }

  /**
   * Attempt to convert a String to a Long in decimal.
   * 
   * @param in
   *          The String to convert
   * @return The Long value of the String, or Null.
   */
  public static Long toLong(final String in) {
    return toLong(in, 10);
  }

  /**
   * Attempt to convert a String to a Long.
   * 
   * @param in
   *          The String to convert.
   * @param radix
   *          The numeric base of the the String.
   * @return The Long value of the String, or Null.
   */
  public static Long toLong(final String in,
      final int radix) {
    if (in != null) {
      try {
        return Long.valueOf(in.trim(), radix);
      } catch (NumberFormatException e) {
      }
    }
    return null;
  }

No comments :

Post a Comment