整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

html固定定位position值fixed

定定位:(1)给自身设置宽高。(2)再设置position:fixed

在公司项目中涉及到一个有大量浮点数价格计算的模块,从而引发了我一系列的思考:

  • 计算机二进制环境下浮点数的计算精度缺失问题;
console.log(0.1 + 0.2);
0.30000000000000004
  • 为了解决上述问题,使用了toFixed方法。却出现了浮点数小数位以5结尾的四舍五入错误问题;
var num = 0.045;
console.log(num.toFixed(2)); // 0.04

以此为起点,引发了我关于toFixed的一系列探索,终于找到了一些有用的信息,toFixed使用的计算规则是:

银行家舍入:所谓银行家舍入法,其实质是一种四舍六入五取偶(又称四舍六入五留双)法。

简单来说就是:四舍六入五考虑,五后非零就进一,五后为零看奇偶,五前为偶应舍去,五前为奇要进一。

下面我们就来证实这个所谓的银行家舍入法,证实分为三种情况,分别以4、5、6为舍入位对toFixed的证实(以chrome为例):

  • 以4为舍入位:
var num = 0.004;
console.log(num.toFixed(2)); // 0.00
var num = 0.014;
console.log(num.toFixed(2)); // 0.01
var num = 0.094;
console.log(num.toFixed(2)); // 0.09

在4结尾这种情况下toFixed表现的还算不错,并没有错误的问题。

  • 以6为舍入位:
var num = 0.006;
console.log(num.toFixed(2)); // 0.01
var num = 0.016;
console.log(num.toFixed(2)); // 0.02
var num = 0.096;
console.log(num.toFixed(2)); // 0.10

以6结尾这种情况下toFixed表现的也不错,并没有错误的问题。

  • 以5为舍入位

5后非零:

var num = 0.0051;
console.log(num.toFixed(2)); // 0.01
var num = 0.0052;
console.log(num.toFixed(2)); // 0.01
var num = 0.0059;
console.log(num.toFixed(2)); // 0.01

根据规则,五后非零就进一,我们证实并没有任何的问题。

5后为零

由于这种情况比较特殊,是toFixed方法出现计算错误的情况,所以我进行了大量的证实,且分别在常见的主流浏览器下进行了测试:

var num = 0.005;
console.log(num.toFixed(2));
var num = 0.015;
console.log(num.toFixed(2));
var num = 0.025;
console.log(num.toFixed(2));
var num = 0.035;
console.log(num.toFixed(2));
var num = 0.045;
console.log(num.toFixed(2));
var num = 0.055;
console.log(num.toFixed(2));
var num = 0.065;
console.log(num.toFixed(2));
var num = 0.075;
console.log(num.toFixed(2));
var num = 0.085;
console.log(num.toFixed(2));
var num = 0.095;
console.log(num.toFixed(2));

chrome、firefox、safari、opera的结果如下:

0.01

0.01

0.03

0.04

0.04

0.06

0.07

0.07

0.09

0.10

ie11结果如下:

0.01

0.02

0.03

0.04

0.05

0.06

0.07

0.08

0.09

0.10

可以看出Ie11下正常,其余浏览器下均出现错误。虽然并不完全符合银行家舍入法的规则,我认为是由于二进制下浮点数的坑导致了不完全符合该规则。

总而言之:不论引入toFixed解决浮点数计算精度缺失的问题也好,它有没有使用银行家舍入法也罢,都是为了解决精度的问题,但是又离不开二进制浮点数的环境,但至少他帮助我们找到了问题所在,从而让我们有解决方法。

解决方法

下面我提供一种通过重写toFixed的方法:

如果你在工作中碰到这个问题,不妨试试,如果好用,可以给我点赞或者打赏一下辛苦费,谢谢(还有一种解决方案放在我之前的文章里面了,如果感兴趣可以翻阅)

参考文章:

http://www.chengfeilong.com/toFixed

定定位(1)给自身设置宽高(2)设置position:fixed(3)底部元素内顶边距