java implements string and number conversion tools

  • 2021-07-22 09:37:15
  • OfStack

This article example for everyone to share the java string and digital conversion tools specific code, for your reference, the specific content is as follows


package com.test.util;

/**
 *  Digital tool class 
 */
public class NumberUtil {

 /**
  *  Convert numbers to strings 
  * @param num  Figures 
  * @return  String , If  num  Empty ,  Returns an empty string 
  */
 public static String num2Str(Object num) {
  String str = null;

  if (num == null) {
   str = "";
  }
  else {
   str = String.valueOf(num);
  }
  return str;
 }

 /**
  *  String is converted to Integer
  * @param str  String 
  * @return Integer, str For null Return when 0
  */
 public static Integer getInteger(Object obj) {
  return getInteger(obj, 0);
 }

 /**
  *  String is converted to Integer
  * @param str  String 
  * @param def  Default value 
  * @return Integer,  The string is null Return when def
  */
 public static Integer getInteger(Object obj, int def) {
  String str = obj == null ? "" : obj.toString();

  Integer i = null;

  if (str.trim().length() == 0) {
   i = new Integer(def);
  }
  else {
   try {
    i = Integer.valueOf(str);
   }
   catch (Exception e) {
   }
  }

  return i == null ? new Integer(def) : i;
 }

 /**
  *  String is converted to Long
  * @param str  String 
  * @return Long, str For null Return when 0
  */
 public static Long getLong(Object obj) {
  return getLong(obj, 0);
 }

 /**
  *  String is converted to Long
  * @param str  String 
  * @param def  Default value 
  * @return Long,  The string is null Return when def
  */
 public static Long getLong(Object obj, long def) {
  String str = obj == null ? "" : obj.toString();

  Long l = null;

  if (str.trim().length() == 0) {
   l = new Long(def);
  }
  else {
   try {
    l = Long.valueOf(str);
   }
   catch (Exception e) {
   }
  }

  return l == null ? new Long(def) : l;
 }

 /**
  *  String is converted to Integer
  * @param str  String 
  * @return Integer, str For null Return when 0
  */
 public static int getIntegerValue(Object obj) {
  return getIntegerValue(obj, 0);
 }

 /**
  *  String is converted to Integer
  * @param str  String 
  * @param def  Default value 
  * @return Integer,  The string is null Return when def
  */
 public static int getIntegerValue(Object obj, int def) {
  return getInteger(obj, def).intValue();
 }

 /**
  *  String is converted to Long
  * @param str  String 
  * @return Long, str For null Return when 0
  */
 public static long getLongValue(Object obj) {
  return getLongValue(obj, 0);
 }

 /**
  *  String is converted to Long
  * @param str  String 
  * @param def  Default value 
  * @return Long,  The string is null Return when def
  */
 public static long getLongValue(Object obj, long def) {
  return getLong(obj, def).longValue();
 }
}

Related articles: