所以(0.1+0.2)!=03
解决这种问题,可以将小数变成整数进行运算,然后再将结果变为小数。
//乘法
function multiNum (a,b){
var c = 0,
d = a.toString(),
e = b.toString()
try {
c += d.split(".")[1].length
} catch (f) { }
try {
c += e.split(".")[1].length
} catch (f) { }
return Number(d.replace(".","")) * Number(e.replace(".","")) / Math.pow(10,c)
}
//除法
function divide (a,b){
var c,d,e = 0,
f = 0
try {
e = a.toString().split(".")[1].length
} catch (g) { }
try {
f = b.toString().split(".")[1].length
} catch (g) { }
return c = Number(a.toString().replace(".","")),d = Number(b.toString().replace(".","")),this.mul(c / d,Math.pow(10,f - e))
}
//加法
function addNum (a,b){
var c,d,e
try {
c = a.toString().split(".")[1].length
} catch (f) {
c = 0
}
try {
d = b.toString().split(".")[1].length
} catch (f) {
d = 0
}
return e = Math.pow(10,Math.max(c,d)),(multiNum(a,e) + multiNum(b,e)) / e
}
//减法
function subNum (a,b) {
var c,d,e
try {
c = a.toString().split(".")[1].length
} catch (f) {
c = 0
}
try {
d = b.toString().split(".")[1].length
} catch (f) {
d = 0
}
return e = Math.pow(10,Math.max(c,d)),(multiNum(a,e) - multiNum(b,e)) / e
}
//加法
Number.prototype.add = function (arg) {
var r1 = 0, r2 = 0, m
//获取小数的位数并取最大值
try { r1 = this.toString().split(".")[1].length } catch (e) { }
try { r2 = arg.toString().split(".")[1].length } catch (e) { }
m = Math.pow(10, Math.max(r1, r2))
return (this * m + arg * m) / m
}
//减法
Number.prototype.sub = function (arg) {
return this.add(-arg)
}
//乘法
Number.prototype.mul = function (arg) {
var m = 0, s1 = this.toString(), s2 = arg.toString()
//小数位数相加
try { m += s1.split(".")[1].length } catch (e) { }
try { m += s2.split(".")[1].length } catch (e) { }
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}
//除法
Number.prototype.div = function (arg) {
var t1 = 0, t2 = 0, r1, r2
try { t1 = this.toString().split(".")[1].length } catch (e) { }
try { t2 = arg.toString().split(".")[1].length } catch (e) { }
//将小数点去掉转换为整数
r1 = Number(this.toString().replace(".", ""))
r2 = Number(arg.toString().replace(".", ""))
return (r1 / r2) * Math.pow(10, t2 - t1)
}