给Number类型增加加法、减、乘、除函数,解决float相加结果精度错乱的问题

2023-05-09,,

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script type="text/javascript">
//给Number类型增加 加法函数
Number.prototype.add = function (arg) {
var l1 = this.toString().indexOf('.') > 0 ? this.toString().split(".")[1].length : 0,
l2 = arg.toString().indexOf('.') > 0 ? arg.toString().split(".")[1].length : 0,
pw = Math.pow(10, Math.max(l1, l2));
return (arg * pw + pw * this) / pw;
};
//给Number类型增加 减法函数
Number.prototype.sub = function (arg) {
var l1 = this.toString().indexOf('.') > 0 ? this.toString().split(".")[1].length : 0,
l2 = arg.toString().indexOf('.') > 0 ? arg.toString().split(".")[1].length : 0,
pw = Math.pow(10, Math.max(l1, l2)),
//动态控制精度长度
l = (l1 >= l2) ? l1 : l2;
return ((this * pw - arg * pw) / pw).toFixed(l);
}
//给Number类型增加 乘法函数
Number.prototype.mul = function (arg) {
var pw = 0;
pw += this.toString().indexOf('.') > 0 ? this.toString().split(".")[1].length : 0;
pw += arg.toString().split(".")[1].length > 0 ? arg.toString().split(".")[1].length : 0;
return Number(arg.toString().replace(".", "")) * Number(this.toString().replace(".", "")) / Math.pow(10, pw);
}
//给Number类型增加 除法函数
Number.prototype.div = function (arg) {
var l1 = this.toString().indexOf('.') > 0 ? this.toString().split(".")[1].length : 0,
l2 = arg.toString().indexOf('.') > 0 ? arg.toString().split(".")[1].length : 0;
with (Math) {
r1 = Number(this.toString().replace(".", ""));
r2 = Number(arg.toString().replace(".", ""));
return (r1 / r2) * pow(10, l2 - l1);
}
}
/*加法函数 调用实例*/
var testadd = [1.123, 2.456, 3.456, 4, 5, 6, 7, 8, 9, 0];
console.log(testadd[0].add(testadd[1])); //3.579
console.log(1.123 + 2.456); //错误对比:3.5789999999999997 var count = 0;
for (i in testadd)
count = count.add(testadd[i]);
console.log(count); //46.035
console.log('加法函数 调用实例'); /*减法函数 调用实例*/
var testsub = [1.123, 2.456, 3.456, 4, 5, 6, 7, 8, 9, 0];
console.log(testsub[1].sub(testsub[0])); //1.333 console.log(testsub[1].sub(testsub[2])); //-1.000
console.log(2.456 - 3.456); //小数对比:-1
console.log('减法函数 调用实例'); /*乘法函数 调用实例*/
var testmul = [1.123, 2.456, 3.456, 4, 5, 6, 7, 8, 9, 0];
console.log(testmul[1].mul(testmul[2])); //8.487936
console.log(2.456 * 3.456); //8.487936
console.log('乘法函数 调用实例'); //乘法函数 调用实例
var testdiv = [1.123, 2.456, 3.456, 4, 5, 6, 7, 8, 9, 0];
console.log(testdiv[1].div(testdiv[2])); //0.7106481481481481
console.log(2.456 / 3.456); //0.7106481481481481
console.log('乘法函数 调用实例');
</script>
</head>
<body> </body>
</html>

  

给Number类型增加加法、减、乘、除函数,解决float相加结果精度错乱的问题的相关教程结束。

《给Number类型增加加法、减、乘、除函数,解决float相加结果精度错乱的问题.doc》

下载本文的Word格式文档,以方便收藏与打印。