JS 浮点值精确计算
from:http://rockyee.iteye.com/blog/891538
1 Number.prototype.toFixed = function(scale){
2 var s = this + "";
3 if (!scale) scale = 0;
4 if (s.indexOf(".") == -1) s += ".";
5 s += new Array(scale + 1).join("0");
6 if (new RegExp("^(-|\\+)?(\\d+(\\.\\d{0," + (scale + 1) + "})?)\\d*$").test(s))
7 {
8 var s = "0" + RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, b = true;
9 if (a == scale + 2)
10 {
11 a = s.match(/\d/g);
12 if (parseInt(a[a.length - 1]) > 4)
13 {
14 for (var i = a.length - 2; i >= 0; i--)
15 {
16 a[i] = parseInt(a[i]) + 1;
17 if (a[i] == 10)
18 {
19 a[i] = 0;
20 b = i != 1;
21 }
22 else
23 break;
24 }
25 }
26 s = a.join("").replace(new RegExp("(\\d+)(\\d{" + scale + "})\\d$"), "$1.$2");
27 }
28 if (b) s = s.substr(1);
29 return (pm + s).replace(/\.$/, "");
30 }
31 return this + "";
32 }
通过正则来四舍五入,覆盖Number原本的toFixed方法
测试:
alert(Number(9.13-9.02));
alert(Number(9.13-9.02).toFixed(2));