Java中Double与BigDecimal的相互转换
今天写代码过程中,发现⼀个Double的变量通过new BigDecimal(Double d)转换为BigDecimal时,有效数字改变了,如下:
public class BigDecimalTest {
public static void main(String[] arg) {
String s1 = "123.45";
Double d1 = new Double(s1);
//使⽤String类型的形参构造BigDecimal
BigDecimal bg1 = new BigDecimal(d1);
//使⽤Double类型的形参构造BigDecimal
BigDecimal bg2 = new BigDecimal(s1);
System.out.println("bg1 = "+bg1);
System.out.println("bg2 = "+bg2);
}
}
输出:
bg1 = 123.4500000000000028421709430404007434844970703125
bigdecimal转换为integerbg2 = 123.45
同样⼤⼩的Double数,以字符串形参的⽅式构造BigDecimal就能得到同样精度。⽽使⽤Double构造就会导致精度改变。事实上,按照官⽅API⽂档,推荐使⽤String形参的⽅式将float、double转换为BidDecimal,⽂档原⽂:For values other than float and double NaN and ±Infinity, this constructor is compatible with the values returned by and . This is generally the preferred way to convert a float or double into a BigDecimal, as it doesn't suffer from the unpredictability of the constructor。不⽌如此,还有以下情况:
public class BigDecimalTest {
public static void main(String[] arg) {
String s1 = "123.45";
String s2 = "123.450";
Double d1 = new Double(s1);
Double d2 = new Double(s2);
BigDecimal bg1 = new BigDecimal(s1);
BigDecimal bg2 = new BigDecimal(s2);
System.out.println("d1.equals(d2): "+d1.equals(d2));
System.out.println("bg1.equals(bg2): "+bg1.equals(bg2));
}
}
Output:
d1.equals(d2): true
bg1.equals(bg2): false
同样⼤⼩的⼩数,有效数字不同情况下,Double类型的⼤⼩⽐较结果是相等的,符合我们的实际计算。但是分别转换成BigDecimal后再⽐较⼤⼩,得到不相等的结果。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论