zoukankan      html  css  js  c++  java
  • 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
    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后再比较大小,得到不相等的结果。

    不闻不若闻之,闻之不若见之,见之不若知之,知之不若行之
  • 相关阅读:
    Zstack中任务,事件,消息之间的关系
    Zigbee折腾之旅:(一)CC2530最小系统
    计算机中原码,反码,补码之间的关系
    Python3
    Python3
    Python3
    【基础】强软弱虚引用
    SpringBoot上传文件时MultipartFile报空问题解决方法
    Mockito中的@Mock和@Spy如何使用
    Vim 多行剪切、复制和删除
  • 原文地址:https://www.cnblogs.com/lauyu/p/5052800.html
Copyright © 2011-2022 走看看