Java中double转BigDecimal的注意事项

Java中double转BigDecimal的注意事项先上结论:不要直接用double变量作为构造BigDecimal的参数。 线上有这么一段Java代码逻辑:1,接口传来一个JSON串,里面有个数字:57.3。2,解析JSON并把这个数字保存在一个float变量。3,把这个float变量赋值给一个BigDecimal对象,用的是BigDecimal的double参数的构造:  newBigDecimal(double…

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

先上结论:不要直接用double变量作为构造BigDecimal的参数。

 

线上有这么一段Java代码逻辑:

1,接口传来一个JSON串,里面有个数字:57.3。

2,解析JSON并把这个数字保存在一个float变量。

3,把这个float变量赋值给一个 BigDecimal对象,用的是BigDecimal的double参数的构造:

   new BigDecimal(double val)

4,把这个BigDecimal保存到MySQL数据库,字段类型是decimal(15,2)。

 

这段代码逻辑在线上跑了好久了,数据库保存的值是57.3也没什么问题,但是在今天debug的时候发现,第三步的BigDecimal对象保存的值并不是57.3,而是57.299999237060546875,很明显,出现了精度的问题。

至于数据库最终保存了正确的57.3完全是因为字段类型设置为2位小数,超过2位小数就四舍五入,所以才得到了正确的结果,相当于MySQL给我们把这个精度问题掩盖了。

 

总觉得这是个坑,所以研究了一下相关的知识。

首先是BigDecimal的double参数构造,在官方JDK文档中对这个构造是这么描述的:

public BigDecimal(double val)

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

Notes:

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

The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal(“0.1”) creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.

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

Parameters:

val – double value to be converted to BigDecimal.

Throws:

NumberFormatException – if val is infinite or NaN.

翻译一下大概是这样的:

1,BigDecimal(double val)构造,用double当参数来构造一个BigDecimal对象。

2,但是这个构造不太靠谱(unpredictable),你可能以为BigDecimal(0.1)就是妥妥的等于0.1,但是你以为你以为的就是你以为的?还真不是,BigDecimal(0.1)这货实际上等于0.1000000000000000055511151231257827021181583404541015625,因为准确的来说0.1本身不能算是一个double(其实0.1不能代表任何一个定长二进制分数)。

3,BigDecimal(String val)构造是靠谱的,BigDecimal(“0.1”)就是妥妥的等于0.1,推荐大家用这个构造。

4,如果你非得用一个double变量来构造一个BigDecimal,没问题,我们贴心的提供了静态方法valueOf(double),这个方法跟new Decimal(Double.toString(double))效果是一样的。

 

说白了就是别直接拿double变量做参数,最好使用String类型做参数或者使用静态方法valueOf(double),我写了个例子试了一下:

         public static void main(String[] args) {



                   float a=57.3f;

                   BigDecimal decimalA=new BigDecimal(a);

                   System.out.println(decimalA);

                  

                   double b=57.3;

                   BigDecimal decimalB=new BigDecimal(b);

                   System.out.println(decimalB);

                  

                   double c=57.3;

                   BigDecimal decimalC=new BigDecimal(Double.toString(c));

                   System.out.println(decimalC);

                  

                   double d=57.3;

                   BigDecimal decimalD=BigDecimal.valueOf(d);

                   System.out.println(decimalD);

         }

 

输出结果:

57.299999237060546875

57.2999999999999971578290569595992565155029296875

57.3

57.3

以后还是尽量按照官方推荐的套路来,否则不知道什么时候又给自己挖坑了。

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

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

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 【ubuntu】修改Ubuntu的apt-get为国内镜像源的方法

    【ubuntu】修改Ubuntu的apt-get为国内镜像源的方法

    2021年7月2日
    85
  • Windows10下安装Git

    Windows10下安装GitGit是一个开源的分布式版本控制系统,可以有效、高速的处理从很小到非常大的项目版本管理。具体安装步骤如下:第一步:先从官网下载最新版本的Git官网地址:https://git-scm.com/downloads点击上图中表示的地方进行下载,得到Git-2.17.1.2-64-bit.exe文件。如果你的系统是32位的,可以通过如下方式下载:第二步:双击下载好的git安装包,弹出提示框,如下图:第三…

    2022年6月11日
    39
  • 布局转模型无法生成新图形_三维数组初始化

    布局转模型无法生成新图形_三维数组初始化本系列文章为原创,转载请注明出处。作者:DongdongBai邮箱:baidongdong@nudt.edu.cn若您觉得本博文对您有帮助,请您为我点赞并关注我,以鼓励我写出更优秀的博文。谢谢!Eigen:C++开源矩阵计算工具——Eigen的简单用法Eigen库是一个开源的C++线性代数库,它提供了快速的有关矩阵的线性代数运算,还包括解方程等功能。Eigen

    2022年10月19日
    4
  • 关系型数据库的发展历史[通俗易懂]

    关系型数据库的发展历史[通俗易懂]数据库发展史信息系统产生了海量的数据,有数据必须要有数据的存放位置,无库时代:没有专门的数据库,数据大多以文件形式存放层次状数据库:使用层次状模型进行数据库设计和存放网状数据库:使用网状模型进行数据库设计和存放关系型数据库:使用关系型模型进行数据库设计和存放非关系型数据库:为适应水平扩展性和处理超大量的数据环境,近几年发展非常迅速的发展,衍生类型非常多。 本

    2022年7月16日
    15
  • windows WinExec()

    windows WinExec()23456#includeintmain(){WinExec(“notepad.exe”,SW_SHOW);//运行计事本return0;}

    2022年7月11日
    22
  • Oracle中的wm_concat函数用法

    Oracle中的wm_concat函数用法    在日常的数据查询过程中,经常遇到一条信息分多条记录存储,并以同一个ID关联的情况,比如常见的房产证权利人信息,因为共有权人可能有很多,不可能把所有的权利人都放到权利人表的权利人字段,把所有权利人的证件号都放到权利人证件号字段,所以在数据库设计时候,会采用一个权利人一条记录,并以权利ID关联的方式存…

    2022年5月26日
    95

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号