代码
const floatObj = function () {
function sum(n1, n2) {
var n1FloatLength, n2FloatLength;
try {
n1FloatLength = n1.toString().split('.')[1].length;
} catch (e) {
n1FloatLength = 0;
}
try {
n2FloatLength = n2.toString().split('.')[1].length;
} catch (e) {
n2FloatLength = 0;
}
var m = Math.pow(10, Math.max(n1FloatLength, n2FloatLength));
return Math.round(n1 * m + n2 * m) / m;
}
function mul(a, b) {
var c = 0,
d = a.toString(),
e = b.toString();
try {
c += d.split(".")[1].length;
} catch (f) { }
try {
c += e.split(".")[1].length;
} catch (f) { }
return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
}
function division(a, b) {
var c, d, e = 0,
f = 0;
try {
e = a.toString().split(".")[1].length;
} catch (g) { }
try {
f = b.toString().split(".")[1].length;
} catch (g) { }
return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), mul(c / d, Math.pow(10, f - e));
}
return {
add: sum,
subtract: function (n1, n2) { return sum(n1, -n2); },
multiply: mul,
divide: division
}
}();
Number.prototype.add = function (arg) {
return floatObj.add(this, arg);
}
Number.prototype.subtract = function (arg) {
return floatObj.subtract(this, arg);
}
Number.prototype.multiply = function (arg) {
return floatObj.multiply(this, arg);
}
Number.prototype.divide = function (arg) {
return floatObj.divide(this, arg);
}
使用示例
const a = 1
const b = 2
let result = {
addValue: undefined, // +
subtractValue: undefined, // -
multiplyValue: undefined, // *
divideValue: undefined, // /
}
result.addValue = a['add']b
result.subtractValue= a['subtract']b
result.multiplyValue= a['multiply']b
result.divideValue= a['divide']b