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后再比较大小,得到不相等的结果。

    不闻不若闻之,闻之不若见之,见之不若知之,知之不若行之
  • 相关阅读:
    定义模块与增加模块中的测试代码
    20150412自省
    Python中暂未解决的问题
    Node基础_文件系统
    Node基础_Buffer缓冲区
    Node基础_npm简介
    Node基础_模块化简介及详解
    Node基础_node简介
    Nosql_Mongoose简介及操作
    Nosql_MongoDB简单的查询练习
  • 原文地址:https://www.cnblogs.com/lauyu/p/5052800.html
Copyright © 2011-2022 走看看