关于Java计算精度问题

作者: 我的天呐0_0 | 来源:发表于2019-05-16 14:01 被阅读6次

初级问题:

double i = 399 * 0.075;

此时结果:29.924999999999997 明显和我们应得的29.925有精度上的问题

so,马上想到了BigDecimal这一高精度计算专用的类

new BigDecimal(399).multiply(new BigDecimal(0.075)).doubleValue();

此时结果:29.924999999999997,说好的高精度计算呢
后发现
Note: the results of this constructor can be somewhat unpredictable. One might assume that new BigDecimal(.1) is exactly equal to .1, but it is actually equal to .1000000000000000055511151231257827021181583404541015625. This is so because .1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to .1, appearances nonwithstanding. The (String) constructor, on the other hand, is perfectly predictable: new BigDecimal(".1") is exactly equal to .1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one.

即构造参数传入double时奇数转换二进制还是存在精度问题,而string就完全ok

最终

`new BigDecimal(399).multiply(new BigDecimal("0.075")).doubleValue();

得到预知结果

相关文章

  • 关于Java计算精度问题

    初级问题: 此时结果:29.924999999999997 明显和我们应得的29.925有精度上的问题 so,马...

  • 2018-11-04-1

    java double计算精度问题 double计算防止精度丢失:方案:将double转成bigDecimalSy...

  • Java浮点数计算精度问题总结

    Java浮点数计算精度问题总结 首先看看下面几个简单的加法计算的输出结果:System.out.println(0...

  • JavaScript 计算精度问题; 科学计数问题

    本篇文章主要解决JavaScript中的计算精度问题和科学计数显示问题。例如:99969998.99999993 ...

  • js精度问题

    关于js浮点数计算精度不准确问题的解决办法 今天在计算商品价格的时候再次遇到js浮点数计算出现误差的问题,以前就一...

  • Js计算精度问题

    最近在做金融类的开发,页面需要一些计算,在计算过程中发现js页面会存在精度问. 例如: 0.1 + 0.2 /...

  • Javascript计算精度问题

    Javascript是弱类型语言,在进行浮点数计算时会有误差出现(这在很多语言中都是存在的,只是其他语言内部会去规...

  • Android(Java)计算精度校正

    现象 得到的f4值是多少?稍有经验的程序员估计都会想「肯定不是0.4」Bingo!答案是0.39999998 原理...

  • 备忘

    1、js中解决数字计算精度问题,math.js bignumber. math.js https://blog.c...

  • 关于float计算精度问题的解决办法

    在编程开发领域,不仅仅是OC这个语言,相信很多语言在数值计算精度方面,使用float类型的值,在进行四则运算时都会...

网友评论

    本文标题:关于Java计算精度问题

    本文链接:https://www.haomeiwen.com/subject/iwqiaqtx.html