zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java double转decimal_Java中Double与BigDecimal的相互转换

JAVA转换 相互 bigdecimal double Decimal
2023-06-13 09:11:41 时间

大家好,又见面了,我是你们的朋友全栈君。

今天写代码过程中,发现一个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

bg2 = 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 Float.toString(float) and Double.toString(double). 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 BigDecimal(double) 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后再比较大小,得到不相等的结果。

时间: 12-15

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/144143.html原文链接:https://javaforall.cn