BigDecimal的问题

本文详细解析了Java中BigDecimal类的构造函数,特别是通过double和String两种方式创建BigDecimal实例的区别。文章强调了使用String构造函数的重要性,并给出了具体的案例说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java Doc解释


public BigDecimal(double val)Translatesa double into a BigDecimal which is the exact decimal representation of thedouble's binary floating-point value. The scale of the returned BigDecimal isthe smallest value such that (10scale × val) is an integer.

Notes:

The results of this constructor can besomewhat unpredictable. One might assume that writing new BigDecimal(0.1) inJava creates a BigDecimal which is exactly equal to 0.1 (an unscaledvalue of 1, with a scale of 1), but it is actually equal to0.1000000000000000055511151231257827021181583404541015625. This is because 0.1cannot be represented exactly as a double (or, for that matter, as a binaryfraction of any finite length). Thus, the value that is being passed in to theconstructor is not exactly equal to 0.1, appearances notwithstanding.

The String constructor, on the otherhand, is perfectly predictable: writing new BigDecimal("0.1") createsa BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, itis generally recommended that the String constructor be used in preference tothis one.

When a double must be used as a sourcefor a BigDecimal, note that this constructor provides an exact conversion; itdoes not give the same result as converting the double to a String using theDouble.toString(double) method and then using the BigDecimal(String)constructor. To get that result, use the static valueOf(double) method. 



案例:

// float / double不能表示精确的小数。
System.out.println(0.01 + 0.09); // 0.09999999999999999
System.out.println(1.0 / 3 * 3);
// BigDecimal
BigDecimal bd1 = new BigDecimal(0.09);
BigDecimal bd2 = new BigDecimal(0.01);
System.out.println(bd1.add(bd2));  // 0.09999999999999999687749774324174723005853593349456787109375

BigDecimal bd3 = new BigDecimal("0.09");
BigDecimal bd4 = new BigDecimal("0.01");
System.out.println(bd3.add(bd4));  // 0.1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值