【Java】常用数据类型转换(BigDecimal、包装类、日期等)

新工作转到大数据方向,每天都要面对数据类型互相转换的工作,再加上先前面试发现这部分的知识盲点,

决定复习之余自己再写一套便捷的方法,以后会比较方便。(虽然公司有现成封装的类,里头还有些遗漏的地方,暂时不敢随便修改 )

1. BigDecimal和基本类型之间的转换

现在蹲在银行里做项目,对数字的精准性要求较高。比起Java里常用的double、int这些数据类型,BigDecimal的好处在于能够设置你想要的精度。

① BigDecimal和字符串String类型

//字符串 → BigDecimal
String a = "1.2";
BigDecimal a2 = new BigDecimal(a);
//Big Decimal → 字符串
BigDecimal b = new BigDecimal("1.2");
String b2 = b.toString();

//使用DecimalFormat可设置精度
DecimalFormat df = new DecimalFormat("0.00");
String b3 = df.format(b);
System.out.println(b2);//1.2
System.out.println(b3);//1.20

② 同理,double和int等数据类型也可与BigDecimal进行转换,但不建议使用double类型进行转换(浮点数没有办法用二进制准确表示)

//浮点型 与 BigDecimal
BigDecimal i = new BigDecimal(1.2);//浮点型
i.doubleValue();
//整型 与 BigDecimal
BigDecimal i2 = new BigDecimal(1);//整型
i.intValue();

关于BigDecimal的具体计算和不建议用浮点数进行BigDecimal转换,可以参照:https://www.cnblogs.com/LeoBoy/p/6056394.html

③BigDecimal的加减乘除

BigDecimal a = new BigDecimal("1");
BigDecimal b = new BigDecimal("2");
		
a.add(b);//加法 a+b
a.subtract(b);//减法 a-b
a.multiply(b);//乘法 axb
a.divide(b);//除法 a/b
int scale = 2;//精度 - 小数点后几位
a.divide(b,scale,BigDecimal.ROUND_HALF_UP);//四舍五入

2. 基本数据类型和包装类之间的转换

在一次面试中,面试官问到装箱拆箱,以及为什么要设置基本数据类型的包装类的问题,后面那个问题答不上。

基本数据类型包装类存在是有理由的,基本数据类型不支持面向对象的编程机制,在集合指定对象类型进行存储时,由于基本数据类型不是对象,所以无法指定,但我们可以用基本数据类型的包装类。在集合使用过程中,包装类会自动拆箱封箱,从而达到存储、获取基本数据类型的功能。

//装箱:基本类型 → 基本类型的包装类
Integer i = 3;
//拆箱: 包装类型 → 基本类型
int ii = i;
ii = new Integer(3);


//基本类型 → 包装类
Integer s1 = Integer.valueOf("1");
Integer s2 = Integer.valueOf(1);
System.out.println(s1==s2);//true, s1,s2指向同一个数值

//Integer之间的比较
Integer i1 = 1;
Integer i2 = 1;
System.out.println(i1==i2);//true
System.out.println(s1==i1);//true

Integer i3 = 150;
Integer i4 = 150;
System.out.println(i3==i4);//false 超出Integer数值范围

//Integer和new Integer的比较,新创建(new)的包装类对象一定与其它包装类不相等
Integer s3 = 1;
Integer s4 = new Integer(1);
Integer s5 = new Integer("1");
System.out.println(s3==s4);//false 
System.out.println(s4==s5);//false


//Integer和int的比较
int c1 = Integer.parseInt("1");
Integer c2 = Integer.parseInt("1");
System.out.println(c1==c2);//Integer与int比较时会把Integer类型转为int类型,比较的是值的大小

3. 日期

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str1 = sdf.format(date);
		
String str2 = "2018年12月12日";
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
try {
    Date date2 = sdf2.parse(str2);//给定的时间格式必须满足或者少于字符串的位数
  } catch (ParseException e) {
    e.printStackTrace();
  }
原文地址:https://www.cnblogs.com/tubybassoon/p/9906049.html