本文实例为大家分享了java字符串和数字转换工具的具体代码,供大家参考,具体内容如下
package com.test.util;
/**
* 数字工具类
*/
public class numberutil {
/**
* 数字转换为字符串
* @param num 数字
* @return 字符串,如果 num 为空, 返回空字符串
*/
public static string num2str(object num) {
string str = null;
if (num == null) {
str = "";
}
else {
str = string.valueof(num);
}
return str;
}
/**
* 字符串转换为integer
* @param str 字符串
* @return integer, str为null时返回0
*/
public static integer getinteger(object obj) {
return getinteger(obj, 0);
}
/**
* 字符串转换为integer
* @param str 字符串
* @param def 默认值
* @return integer, 字符串为null时返回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;
}
/**
* 字符串转换为long
* @param str 字符串
* @return long, str为null时返回0
*/
public static long getlong(object obj) {
return getlong(obj, 0);
}
/**
* 字符串转换为long
* @param str 字符串
* @param def 默认值
* @return long, 字符串为null时返回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;
}
/**
* 字符串转换为integer
* @param str 字符串
* @return integer, str为null时返回0
*/
public static int getintegervalue(object obj) {
return getintegervalue(obj, 0);
}
/**
* 字符串转换为integer
* @param str 字符串
* @param def 默认值
* @return integer, 字符串为null时返回def
*/
public static int getintegervalue(object obj, int def) {
return getinteger(obj, def).intvalue();
}
/**
* 字符串转换为long
* @param str 字符串
* @return long, str为null时返回0
*/
public static long getlongvalue(object obj) {
return getlongvalue(obj, 0);
}
/**
* 字符串转换为long
* @param str 字符串
* @param def 默认值
* @return long, 字符串为null时返回def
*/
public static long getlongvalue(object obj, long def) {
return getlong(obj, def).longvalue();
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持萬仟网。
希望与广大网友互动??
点此进行留言吧!