常用的数字加减乘除方法的封装
在我们日常的开发者,经常会遇到需要对数字进行加减乘除的操作;
日常的(+,-,*,/)运算符在进行小数的计算时可能会影响数据的准确性,下面简单介绍一下能准确计算出结果的实现方法。
在编写方法之前首先要知道js的isNaN()函数的作用;
isNaN() 函数可用于判断其参数是否是 NaN,该值表示一个非法的数字(比如被 0 除后得到的果)。
如果把 NaN 与任何值(包括其自身)相比得到的结果均是 false,
所以要判断某个值是否是 NaN,不能使用 == 或 === 运算符。正因为如此,isNaN() 函数是必需的。
对于加减法需要基于下面的乘法进行实现
- 加法的实现
function add(a, b){
if(isNaN(a) || isNaN(b) || a == null || b==null){
return 0
}
let c, d;
try{
c = a.toString().split(",")[1].length
}catch (f){
c = 0
}
try{
d = b.toString().split(",")[1].length
}catch (f){
d = 0
}
let e = Math.pow(10, Math.max(c,d))
return mul(a, e) + mul(b, e)/e
}
- 减法的实现
function sub(a, b) {
if(isNaN(a) || isNaN(b) || a == null || b == null){
return 0;
}
let c, d;
try {
c = a.toString().split(".")[1].length;
} catch (f) { c = 0 }
try {
d = b.toString().split(".")[1].length;
} catch (f) {d = 0}
let e = Math.pow(10, Math.max(c, d))
return (mul(a, e) - mul(b, e)) / e;
}
- 乘法的实现
function mul(a, b){
//使用isNaN方法判断入参是否都为数字
if(isNaN(a) || isNaN(b) || a == null || b==null){
return 0
}
let c = 1;
try{
c += a.toString().split(",")[1].length
}catch (){ }
try{
c += b.toString().split(",")[1].length
}catch (){ }
let d= Math.pow(10, c)
return Number(a.toString().replace(".", "")) * Number(b.toString().replace(".", ""))/d
}
- 除法的实现
function div(a, b){
if(isNaN(a) || isNaN(b) || a == null || b==null){
return 0
}
let c, d;
try{
c = a.toString().split(",")[1].length || 0
}catch (){ }
try{
d = b.toString().split(",")[1].length || 0
}catch (){}
let e = Number(a.toString().replace(".", ""))/ Number(b.toString().replace(".", ""))/d
return mul(e,Math.pow(10, d-c))
}