定定位:(1)給自身設置寬高。(2)再設置position:fixed
言
在公司項目中涉及到一個有大量浮點數價格計算的模塊,從而引發了我一系列的思考:
console.log(0.1 + 0.2); 0.30000000000000004
var num = 0.045; console.log(num.toFixed(2)); // 0.04
以此為起點,引發了我關于toFixed的一系列探索,終于找到了一些有用的信息,toFixed使用的計算規則是:
銀行家舍入:所謂銀行家舍入法,其實質是一種四舍六入五取偶(又稱四舍六入五留雙)法。
簡單來說就是:四舍六入五考慮,五后非零就進一,五后為零看奇偶,五前為偶應舍去,五前為奇要進一。
下面我們就來證實這個所謂的銀行家舍入法,證實分為三種情況,分別以4、5、6為舍入位對toFixed的證實(以chrome為例):
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表現的還算不錯,并沒有錯誤的問題。
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后非零:
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)底部元素內頂邊距
*請認真填寫需求信息,我們會在24小時內與您取得聯系。