java实现字符串和数字转换工具
时间:2022-03-11 08:51:55|栏目:JAVA代码|点击: 次
本文实例为大家分享了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();
}
}
上一篇:java 如何使用org.w3c.dom操作XML文件
栏 目:JAVA代码
下一篇:深入理解Java注解的使用方法
本文标题:java实现字符串和数字转换工具
本文地址:http://www.codeinn.net/misctech/195888.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




