1 四舍五入
eg: (1.23).round() = 1.2
(1.2456).round(3) = 1.246
Number.prototype.round = function (count) { var res = 0; var val = this.toString(); var num = parseInt(count || 2); var dataArr = val.split('.'); var arr1 = dataArr[0] || ""; var arr2 = dataArr[1] || ""; var newArr2 = arr2; if (arr2.length > num) { var lastNum = arr2.substring(num, num + 1); if (parseInt(lastNum) >= 5) { newArr2 = parseInt(newArr2.substring(0, num)) + 1; newArr2 = newArr2.toString(); if(newArr2.lengthnum) { arr1 = (parseInt(arr1) + 1).toString(); newArr2 = newArr2.substring(1, 3); } } } val = parseFloat(arr1 + '.' + newArr2); res = parseFloat(val.toFixed(num)); return res; }
2 加减乘除
eg: (1).plus(2) = 3
if (!Number.prototype.plus) { //'+' Number.prototype.plus = function (addend) { var arg1 = this, arg2 = addend; var r1, r2, m, num1, num2; 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)); num1 = r1 == 0 ? parseInt(arg1 * m) : (parseInt(`${arg1.toString().replace('.', '')}`) * m / (Math.pow(10, r1))); num2 = r2 == 0 ? parseInt(arg2 * m) : (parseInt(`${arg2.toString().replace('.', '')}`) * m / (Math.pow(10, r2))); return (num1 + num2) / m; }}if (!Number.prototype.minus) { //'-' Number.prototype.minus = function (Subtraction) { var arg1 = this, arg2 = Subtraction; var r1, r2, m, n, num1, num2; 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; num1 = r1 == 0 ? parseInt(arg1 * m) : (parseInt(`${arg1.toString().replace('.', '')}`) * m / (Math.pow(10, r1))); num2 = r2 == 0 ? parseInt(arg2 * m) : (parseInt(`${arg2.toString().replace('.', '')}`) * m / (Math.pow(10, r2))); return parseFloat(((num1 - num2) / m).toFixed(n)); }}if (!Number.prototype.multiply) { //'*' Number.prototype.multiply = function (multiple) { var arg1 = this, arg2 = multiple; 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) } if (!Number.prototype.devide) { //'/' Number.prototype.devide = function (divisor) { var arg1 = this, arg2 = divisor; 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).multiply(Math.pow(10, t2 - t1)); } }}