JAVA 把字符串转换成数字类型

mport java.math.BigDecimal;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;


public class T {
	public static void main(String[] args) {
		String content = "2147483648";
		Double d = strToNum(content, Double.class);
		Long l = strToNum(content, Long.class);
		Integer i = strToNum(content, Integer.class);
		Float f = strToNum(content, Float.class);
		Byte b = strToNum(content, Byte.class);
		Short s = strToNum(content, Short.class);
		System.out.println("content " + content + " Double " + d + "  Long " + l + " Integer " + i + " Float " + f
				+ " Short " + s + " Byte " + b);
	}

	// 把字符串转换成数字类型
	@SuppressWarnings({ "hiding" })
	public static  T strToNum(String content, Class classz) {
		if (StringUtils.isBlank(content))
			return null;
		String pattern = "^\\-?\\d+\\.?\\d*$";
		// 判断是否是数字
		boolean isMatch = Pattern.matches(pattern, content);
		if (!isMatch)
			return null;
		BigDecimal bd = new BigDecimal(content);
		// 超长处理,进行四舍五入操作,并返回对应类型的值
		Object ob = null;
		int rp = BigDecimal.ROUND_HALF_UP;// 舍入方式
		if (classz.equals(Double.class))
			if (bd.compareTo(new BigDecimal(Double.MAX_VALUE)) > 0)
				ob = Double.MAX_VALUE;
			else if (bd.compareTo(new BigDecimal(Double.MIN_VALUE)) < 0)
				ob = Double.MIN_VALUE;
			else
				ob = bd.setScale(0, rp).doubleValue();
		else if (classz.equals(Long.class))
			if (bd.compareTo(new BigDecimal(Long.MAX_VALUE)) > 0)
				ob = Long.MAX_VALUE;
			else if (bd.compareTo(new BigDecimal(Long.MIN_VALUE)) < 0)
				ob = Long.MIN_VALUE;
			else
				ob = bd.setScale(0, rp).longValue();
		else if (classz.equals(Integer.class))
			if (bd.compareTo(new BigDecimal(Integer.MAX_VALUE)) > 0)
				ob = Integer.MAX_VALUE;
			else if (bd.compareTo(new BigDecimal(Integer.MIN_VALUE)) < 0)
				ob = Integer.MIN_VALUE;
			else
				ob = bd.setScale(0, rp).intValue();
		else if (classz.equals(Float.class))
			if (bd.compareTo(new BigDecimal(Float.MAX_VALUE)) > 0)
				ob = Float.MAX_VALUE;
			else if (bd.compareTo(new BigDecimal(Float.MIN_VALUE)) < 0)
				ob = Float.MIN_VALUE;
			else
				ob = bd.setScale(0, rp).floatValue();
		else if (classz.equals(Byte.class))
			if (bd.compareTo(new BigDecimal(Byte.MAX_VALUE)) > 0)
				ob = Byte.MAX_VALUE;
			else if (bd.compareTo(new BigDecimal(Byte.MIN_VALUE)) < 0)
				ob = Byte.MIN_VALUE;
			else
				ob = bd.setScale(0, rp).byteValue();
		else if (classz.equals(Short.class))
			if (bd.compareTo(new BigDecimal(Short.MAX_VALUE)) > 0)
				ob = Short.MAX_VALUE;
			else if (bd.compareTo(new BigDecimal(Short.MIN_VALUE)) < 0)
				ob = Short.MIN_VALUE;
			else
				ob = bd.setScale(0, rp).shortValue();
		return classz.cast(ob);
	}
}
console:
content 2147483648 Double 2.147483648E9  Long 2147483648 Integer 2147483647 Float 2.14748365E9 Short 32767 Byte 127

 

你可能感兴趣的:(java基础)