1 四舍五入
eg: (1.23).round() = 1.2
(1.2456).round(3) = 1.246
Number.prototype.round = function (count) {
var res = ;
var val = this.toString();
var num = parseInt(count || );
var dataArr = val.split('.');
var arr1 = dataArr[] || "";
var arr2 = dataArr[] || "";
var newArr2 = arr2;
if (arr2.length > num) {
var lastNum = arr2.substring(num, num + );
if (parseInt(lastNum) >= ) {
newArr2 = parseInt(newArr2.substring(, num)) + ;
newArr2 = newArr2.toString();
if(newArr2.length<num){
for(var i =; i< (num - newArr2.length); i ++){
newArr2 = "" + newArr2;
}
}
else if (newArr2.length > num) {
arr1 = (parseInt(arr1) + ).toString();
newArr2 = newArr2.substring(, );
}
}
} 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(".")[].length;
} catch (e) {
r1 =
}
try {
r2 = arg2.toString().split(".")[].length;
} catch (e) {
r2 =
}
m = Math.pow(, Math.max(r1, r2));
num1 = r1 == ? parseInt(arg1 * m) : (parseInt(`${arg1.toString().replace('.', '')}`) * m / (Math.pow(, r1)));
num2 = r2 == ? parseInt(arg2 * m) : (parseInt(`${arg2.toString().replace('.', '')}`) * m / (Math.pow(, 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(".")[].length
} catch (e) {
r1 =
}
try {
r2 = arg2.toString().split(".")[].length
} catch (e) {
r2 =
}
m = Math.pow(, Math.max(r1, r2));
n = (r1 >= r2) ? r1 : r2;
num1 = r1 == ? parseInt(arg1 * m) : (parseInt(`${arg1.toString().replace('.', '')}`) * m / (Math.pow(, r1)));
num2 = r2 == ? parseInt(arg2 * m) : (parseInt(`${arg2.toString().replace('.', '')}`) * m / (Math.pow(, r2)));
return parseFloat(((num1 - num2) / m).toFixed(n));
}
} if (!Number.prototype.multiply) { //'*'
Number.prototype.multiply = function (multiple) {
var arg1 = this,
arg2 = multiple;
var m = ,
s1 = arg1.toString(),
s2 = arg2.toString();
try {
m += s1.split(".")[].length
} catch (e) { }
try {
m += s2.split(".")[].length
} catch (e) { }
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(, m)
} if (!Number.prototype.devide) { //'/'
Number.prototype.devide = function (divisor) {
var arg1 = this,
arg2 = divisor;
var t1 = ,
t2 = ,
r1,
r2;
try {
t1 = arg1.toString().split(".")[].length
} catch (e) { }
try {
t2 = arg2.toString().split(".")[].length
} catch (e) { }
r1 = Number(arg1.toString().replace(".", ""))
r2 = Number(arg2.toString().replace(".", ""))
return (r1 / r2).multiply(Math.pow(, t2 - t1));
}
}
}