您好,欢迎访问一九零五行业门户网

关于js浮点计算问题的详解

分析javascript 只有一种数字类型 number ,而且在javascript中所有的数字都是以ieee-754标准格式表示的。 浮点数的精度问题不是javascript特有的,因为有些小数以二进制表示位数是无穷的:
0.1              0.0001100110011001100110011001100110011001100110011001101 0.2              0.001100110011001100110011001100110011001100110011001101 0.3              0.010011001100110011001100110011001100110011001100110011 0.5              0.1 0.6              0.10011001100110011001100110011001100110011001100110011
所以比如 1.1 ,其程序实际上无法真正的表示 ‘1.1’,而只能做到一定程度上的准确,这是无法避免的精度丢失:
1.09999999999999999
在javascript中问题还要复杂些,这里只给一些在chrome中测试数据:
 输入               输出1.0-0.9 == 0.1     false1.0-0.8 == 0.2     false1.0-0.7 == 0.3     false1.0-0.6 == 0.4     true1.0-0.5 == 0.5     true1.0-0.4 == 0.6     true1.0-0.3 == 0.7     true1.0-0.2 == 0.8     true1.0-0.1 == 0.9     true
解决那如何来避免这类 ` 1.0-0.9 != 0.1 ` 的非bug型问题发生呢?下面给出一种目前用的比较多的解决方案, 在判断浮点运算结果前对计算结果进行精度缩小,因为在精度缩小的过程总会自动四舍五入:
(1.0-0.9).tofixed(digits)     // tofixed() 精度参数须在 0 与20 之间(1.0-0.9).tofixed(10)== 0.1   // 结果为true(1.0-0.8).tofixed(10)== 0.2   // 结果为true(1.0-0.7).tofixed(10)== 0.3   // 结果为true(11.0-11.8).tofixed(10) == -0.8   // 结果为trueparsefloat((1.0-0.9).tofixed(10)) === 0.1   // 结果为trueparsefloat((1.0-0.8).tofixed(10)) === 0.2   // 结果为trueparsefloat((1.0-0.7).tofixed(10)) === 0.3   // 结果为trueparsefloat((11.0-11.8).tofixed(10)) === -0.8   // 结果为true
方法提炼// 通过isequal工具方法判断数值是否相等function isequal(number1, number2, digits){     digits = digits || 10; // 默认精度为10return number1.tofixed(digits) === number2.tofixed(digits); } isequal(1.0-0.7, 0.3);  // return true// 原生扩展方式,更喜欢面向对象的风格number.prototype.isequal = function(number, digits){     digits = digits || 10; // 默认精度为10return this.tofixed(digits) === number.tofixed(digits); } (1.0-0.7).isequal(0.3); // return true

以上就是关于js浮点计算问题的详解的详细内容。
其它类似信息

推荐信息