java实现字符串和数字转换工具

本文实例为大家分享了java字符串和数字转换工具的具体代码,供大家参考,具体内容如下

创新互联建站基于分布式IDC数据中心构建的平台为众多户提供四川电信机房托管 四川大带宽租用 成都机柜租用 成都服务器租用。

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实现字符串和数字转换工具
分享链接:https://www.cdcxhl.com/article44/pgophe.html

成都网站建设公司_创新互联,为您提供微信公众号ChatGPT小程序开发电子商务响应式网站做网站

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

商城网站建设