【浮点数运算加减乘除】
/*加法:浮点数加法的解决方式(原理是将数字转化成相同位数的小数后,再用字符串去掉小数点转化成整数后相加,最后的结果除以其最大的放大倍数)*/
function Add(arg1, arg2) {
var r1, r2, m, c;
try {
r1 = arg1.toString().split(".")[1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = arg2.toString().split(".")[1].length;
} catch (e) {
r2 = 0;
}
c = Math.abs(r1 - r2);
m = Math.pow(10, Math.max(r1, r2));
if (c > 0) {
var cm = Math.pow(10, c);
if (r1 > r2) {
arg1 = Number(arg1.toString().replace(".", ""));
arg2 = Number(arg2.toString().replace(".", "")) * cm;
} else {
arg1 = Number(arg1.toString().replace(".", "")) * cm;
arg2 = Number(arg2.toString().replace(".", ""));
}
} else {
arg1 = Number(arg1.toString().replace(".", ""));
arg2 = Number(arg2.toString().replace(".", ""));
}
return (arg1 + arg2) / m;
}
console.log(Add(0.1, 0.2))
/*减法:解决小数相减的时候,出现的浮点数的问题(原理:判断其小数的位数,放大小数位数当中,10*最大的倍数相减以后,再除,最后保留的位数以最多的为准)*/
function Sub(arg1, arg2) {
var r1, r2, m, n;
try {
r1 = arg1.toString().split(".")[1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = arg2.toString().split(".")[1].length;
} catch (e) {
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2));
n = (r1 >= r2) ? r1 : r2;
return ((arg1 * m - arg2 * m) / m).toFixed(n);
}
console.log(Sub(18.6, 8))
/*乘法:解决小数位数相乘的时候,出现浮点数的问题(将数字转成字符串,并将点转化成空,相当于扩大倍数成为整数,再将他们相乘后除以总共放大的倍数即可)*/
function Mul(arg1, arg2) {
var m = 0,
s1 = arg1.toString(),
s2 = arg2.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);
}
console.log(Mul(7, 0.8))
/*除法:解决小数位数相除的时候,出现的浮点数(获取各参数其带的小数的位数,然后将去掉小数点的方式,将各参数扩大成整数后彼此相除,最后除以10的其彼此的小数位数的差值的立方值。*/
function Div(arg1, arg2) {
var t1 = 0,
t2 = 0,
r1, r2;
try {
t1 = arg1.toString().split(".")[1].length;
} catch (e) {}
try {
t2 = arg2.toString().split(".")[1].length;
} catch (e) {}
r1 = Number(arg1.toString().replace(".", ""));
r2 = Number(arg2.toString().replace(".", ""));
return (r1 / r2) * Math.pow(10, t2 - t1);
}
console.log(Div(1, 0.3))
网友评论