JavaScript浮点数运算的精度问题

之前在做浮点数计算时,偶然发现计算结果有误差,度娘了解了下,补充整理了下。

误差是什么样子的呢?举例

console.log(0.1+0.2); // 0.30000000000000004

事实上在很多的编程语言当中都存在着或多或少的精度问题,只不过类似于Java这些语言经历这么多年,已经封装好了很多方法来解决这个问题了。而JavaScript是一门弱类型的语言,从设计思想上就没有对浮点数这个严格的数据类型,所以精度误差的问题就较为明显。

产生原因:计算机只能识别二进制的数,所以我们将0.1和0.2转为二进制来看下结果

0.1 => 0.0001 1001 1001 1001…(无限循环)
0.2 => 0.0011 0011 0011 0011…(无限循环)

无限循环了,而计算机是不允许无限循环的,所以会进行舍入处理。即使是双精度浮点数,它的小数部分最多也只支持52位,所以两者相加之后会得到这么一串 0.0100110011001100110011001100110011001100110011001100 因浮点数小数位的限制而截断的二进制数字,这时候,我们再把它转换为十进制,就成了 0.30000000000000004。

解决方案

1、 指定要保留的小数位数(0.1+0.2).toFixed(1) = 0.3;这个方法toFixed是进行四舍五入的也不是很精准,对于计算金额这种严谨的问题,不推荐使用,而且不同浏览器对toFixed的计算结果也存在差异。

2、把需要计算的数字升级(乘以10的n次幂)成计算机能够精确识别的整数,等计算完毕再降级(除以10的n次幂),这是大部分编程语言处理精度差异的通用方法。

(0.1 * 10 + 0.2 * 10) / 10 == 0.3 // true

在网上看到的一个修复方法

  1 * ** method **
  2  *  add / subtract / multiply /divide
  3  *
  4  * ** explame **
  5  *  0.1 + 0.2 == 0.30000000000000004 (多了 0.00000000000004  6  *  0.2 + 0.4 == 0.6000000000000001  (多了 0.0000000000001  7  *  19.9 * 100 == 1989.9999999999998 (少了 0.0000000000002  8  *
  9  * floatObj.add(0.1, 0.2) >> 0.3
 10  * floatObj.multiply(19.9, 100) >> 1990
 11  *
 12  */
 13 var floatObj = function() {
 14  
 15     /*
 16      * 判断obj是否为一个整数
 17      */
 18     function isInteger(obj) {
 19         return Math.floor(obj) === obj
 20     }
 21  
 22     /*
 23      * 将一个浮点数转成整数,返回整数和倍数。如 3.14 >> 314,倍数是 100
 24      * @param floatNum {number} 小数
 25      * @return {object}
 26      *   {times:100, num: 314}
 27      */
 28     function toInteger(floatNum) {
 29         var ret = {times: 1, num: 0}
 30         if (isInteger(floatNum)) {
 31             ret.num = floatNum
 32             return ret
 33         }
 34         var strfi  = floatNum + ''
 35         var dotPos = strfi.indexOf('.')
 36         var len    = strfi.substr(dotPos+1).length
 37         var times  = Math.pow(10, len)
 38         var intNum = parseInt(floatNum * times + 0.5, 10)
 39         ret.times  = times
 40         ret.num    = intNum
 41         return ret
 42     }
 43  
 44     /*
 45      * 核心方法,实现加减乘除运算,确保不丢失精度
 46      * 思路:把小数放大为整数(乘),进行算术运算,再缩小为小数(除)
 47      *
 48      * @param a {number} 运算数1
 49      * @param b {number} 运算数2
 50      * @param digits {number} 精度,保留的小数点数,比如 2, 即保留为两位小数
 51      * @param op {string} 运算类型,有加减乘除(add/subtract/multiply/divide)
 52      *
 53      */
 54     function operation(a, b, digits, op) {
 55         var o1 = toInteger(a)
 56         var o2 = toInteger(b)
 57         var n1 = o1.num
 58         var n2 = o2.num
 59         var t1 = o1.times
 60         var t2 = o2.times
 61         var max = t1 > t2 ? t1 : t2
 62         var result = null
 63         switch (op) {
 64             case 'add':
 65                 if (t1 === t2) { // 两个小数位数相同
 66                     result = n1 + n2
 67                 } else if (t1 > t2) { // o1 小数位 大于 o2
 68                     result = n1 + n2 * (t1 / t2)
 69                 } else { // o1 小数位 小于 o2
 70                     result = n1 * (t2 / t1) + n2
 71                 }
 72                 return result / max
 73             case 'subtract':
 74                 if (t1 === t2) {
 75                     result = n1 - n2
 76                 } else if (t1 > t2) {
 77                     result = n1 - n2 * (t1 / t2)
 78                 } else {
 79                     result = n1 * (t2 / t1) - n2
 80                 }
 81                 return result / max
 82             case 'multiply':
 83                 result = (n1 * n2) / (t1 * t2)
 84                 return result
 85             case 'divide':
 86                 result = (n1 / n2) * (t2 / t1)
 87                 return result
 88         }
 89     }
 90  
 91     // 加减乘除的四个接口
 92     function add(a, b, digits) {
 93         return operation(a, b, digits, 'add')
 94     }
 95     function subtract(a, b, digits) {
 96         return operation(a, b, digits, 'subtract')
 97     }
 98     function multiply(a, b, digits) {
 99         return operation(a, b, digits, 'multiply')
100     }
101     function divide(a, b, digits) {
102         return operation(a, b, digits, 'divide')
103     }
104  
105     // exports
106     return {
107         add: add,
108         subtract: subtract,
109         multiply: multiply,
110         divide: divide
111     }
112 }();
113  
114 // toFixed 修复
115 function toFixed(num, s) {
116     var times = Math.pow(10, s)
117     var des = num * times + 0.5
118     des = parseInt(des, 10) / times
119     return des + ''
120 }
原文地址:https://www.cnblogs.com/ruo-shui-yi-fang/p/11409569.html