/** * The function for decimal's add, subtract, multiplication, division. Not get the float result. * And add the function to Number's prototype, so you can use it as: * var result = dcmAdd(0.2,0.1); //or var result = (0.2).add(0.1); * */ function floatAdd(arg1, arg2) { var r1, r2, m, n; try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 } try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 } n = Math.max(r1, r2); // (不加这个还是有问题,如68.04+16.17,因为在下面的arg1*m时会出现浮点数, m = Math.pow(10, n); // 当然也可以用dcmMul(arg1,m)来解决,但考虑到效率还是加这个吧。) return ((arg1 * m + arg2 * m) / m).toFixed(n); } function floatSbt(arg1, arg2) { var r1, r2, m, n; try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 } try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 } n = Math.max(r1, r2);// (不加这个还是有问题,如68.04-16.17) m = Math.pow(10, n); return ((arg1 * m - arg2 * m) / m).toFixed(n); } function floatMul(arg1, arg2) { 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); } function floatDiv(arg1, arg2) { 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) * Math.pow(10, t2 - t1); }; Number.prototype.succ = function() { return this + 1; }, Number.prototype.add = function(arg) { return floatAdd(this, arg); }, Number.prototype.sub = function(arg) { return floatSbt(this, arg); }, Number.prototype.mul = function(arg) { return floatMul(this, arg); }, Number.prototype.div = function(arg) { return floatDiv(this, arg); } Number.prototype.succ = function() { return this + 1; }, String.prototype.add = function(arg) { return floatAdd(this, arg); }, String.prototype.sub = function(arg) { return floatSbt(this, arg); }, String.prototype.mul = function(arg) { return floatMul(this, arg); }, String.prototype.div = function(arg) { return floatDiv(this, arg); }