<!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>