溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java實(shí)現(xiàn)字符串和數(shù)字轉(zhuǎn)換工具

發(fā)布時(shí)間:2020-10-14 09:46:08 來源:腳本之家 閱讀:178 作者:我的半畝田 欄目:編程語言

本文實(shí)例為大家分享了java字符串和數(shù)字轉(zhuǎn)換工具的具體代碼,供大家參考,具體內(nèi)容如下

package com.test.util;

/**
 * 數(shù)字工具類
 */
public class NumberUtil {

 /**
  * 數(shù)字轉(zhuǎn)換為字符串
  * @param num 數(shù)字
  * @return 字符串,如果 num 為空, 返回空字符串
  */
 public static String num2Str(Object num) {
  String str = null;

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

 /**
  * 字符串轉(zhuǎn)換為Integer
  * @param str 字符串
  * @return Integer, str為null時(shí)返回0
  */
 public static Integer getInteger(Object obj) {
  return getInteger(obj, 0);
 }

 /**
  * 字符串轉(zhuǎn)換為Integer
  * @param str 字符串
  * @param def 默認(rèn)值
  * @return Integer, 字符串為null時(shí)返回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;
 }

 /**
  * 字符串轉(zhuǎn)換為Long
  * @param str 字符串
  * @return Long, str為null時(shí)返回0
  */
 public static Long getLong(Object obj) {
  return getLong(obj, 0);
 }

 /**
  * 字符串轉(zhuǎn)換為Long
  * @param str 字符串
  * @param def 默認(rèn)值
  * @return Long, 字符串為null時(shí)返回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;
 }

 /**
  * 字符串轉(zhuǎn)換為Integer
  * @param str 字符串
  * @return Integer, str為null時(shí)返回0
  */
 public static int getIntegerValue(Object obj) {
  return getIntegerValue(obj, 0);
 }

 /**
  * 字符串轉(zhuǎn)換為Integer
  * @param str 字符串
  * @param def 默認(rèn)值
  * @return Integer, 字符串為null時(shí)返回def
  */
 public static int getIntegerValue(Object obj, int def) {
  return getInteger(obj, def).intValue();
 }

 /**
  * 字符串轉(zhuǎn)換為Long
  * @param str 字符串
  * @return Long, str為null時(shí)返回0
  */
 public static long getLongValue(Object obj) {
  return getLongValue(obj, 0);
 }

 /**
  * 字符串轉(zhuǎn)換為Long
  * @param str 字符串
  * @param def 默認(rèn)值
  * @return Long, 字符串為null時(shí)返回def
  */
 public static long getLongValue(Object obj, long def) {
  return getLong(obj, def).longValue();
 }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI