基本数据类型、包装数据类型、BigDecimal使用注意事项

转载:https://blog.csdn.net/qq_34721505/article/details/118541444

	public static void main(String[] args) {
		/**
		 * 所有的POJO都使用包装数据类型;
		 * 所有的RPC调用参数和返回值都使用包装数据类型;
		 * 所有的局部变量都使用基本数据类型;
		 */
		/**
		 * 对于 Integer在-128 至 127 之间的赋值,Integer对象是在 IntegerCache.cache 产生,
			会复用已有对象,这个区间内的 Integer 值可以直接使用==进行判断,但是这个区间之外的所有数据,都
			会在堆上产生,并不会复用已有对象,这是一个大坑,推荐使用 equals 方法进行判断。
		 */
		Integer v1 = 134;
		Integer v2 = 133 + 1;
		System.out.println(v1 == v2); // false
 
		Integer v3 = 126;
		Integer v4 = 127 - 1;
		System.out.println(v3 == v4); // true
		
		int v5 = 126;
		int v6 = 127 - 1;
		System.out.println(v5 == v6); // true
		
		Integer v7 = 122;
		int v8 = 120 + 2;
		System.out.println(v7 == v8); // true
		
		/**
		 * 浮点数之间的等值判断,基本数据类型不能用==来比较,包装数据类型不能用 equals来判断。
			说明:浮点数采用“尾数+阶码”的编码方式,类似于科学计数法的“有效数字+指数”的表示方式。
			二进制无法精确表示大部分的十进制小数
		 */
		float f1 = 1.2f-0.9f;
		float f2 = 0.3f;
		System.out.println(f1 == f2); // false
		
		double d1 = 2.2d-0.9d;
		double d2 = 1.3d;
		System.out.println(d1 == d2); // false
		
		Float f3 = 1.21f + 0.8f;
		Float f4 = 2.01f;
		System.out.println(f3.equals(f4)); // true
		
		// 使用 BigDecimal 来定义值,再进行浮点数的运算操作。
		BigDecimal a = new BigDecimal("1.0");
		BigDecimal b = new BigDecimal("0.9");
		BigDecimal c = new BigDecimal("0.8");
		BigDecimal x = a.subtract(b);
		BigDecimal y = b.subtract(c);
		if (x.equals(y)) {
		 System.out.println("true");
		}
		
		/**
		 * 禁止使用构造方法 BigDecimal(double)的方式把 double 值转化为 BigDecimal 对象。
			说明:BigDecimal(double)存在精度损失风险,在精确计算或值比较的场景中可能会导致业务逻辑异常。
			如:BigDecimal g = new BigDecimal(0.1f); 实际的存储值为:0.10000000149
			优先推荐入参为 String 的构造方法,或使用 BigDecimal 的 valueOf 方法,此方法内部其实执行了
			Double 的 toString,而 Double 的 toString 按 double 的实际能表达的精度对尾数进行了截断。
		 */
		BigDecimal recommend1 = new BigDecimal("0.1");
	 	BigDecimal recommend2 = BigDecimal.valueOf(0.1);
 
	}
         public static void main(String[] args) {
 
 
 
                   float a=57.3f;
 
                   BigDecimal decimalA=new BigDecimal(a);
 
                   System.out.println(decimalA);
 
                  
 
                   double b=57.3;
 
                   BigDecimal decimalB=new BigDecimal(b);
 
                   System.out.println(decimalB);
 
                  
 
                   double c=57.3;
 
                   BigDecimal decimalC=new BigDecimal(Double.toString(c));
 
                   System.out.println(decimalC);
 
                  
 
                   double d=57.3;
 
                   BigDecimal decimalD=BigDecimal.valueOf(d);
 
                   System.out.println(decimalD);
 
         }
输出结果:
57.299999237060546875

57.2999999999999971578290569595992565155029296875

57.3

57.3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值