js关于精确计算和数值格式化以及直接引js文件

时间:2021-05-26

复制代码 代码如下:
(function () {
var calc = {

Add: function (arg1, arg2,d) {
arg1 = arg1.toString(), arg2 = arg2.toString();
var arg1Arr = arg1.split("."), arg2Arr = arg2.split("."), d1 = arg1Arr.length == 2 ? arg1Arr[1] : "", d2 = arg2Arr.length == 2 ? arg2Arr[1] : "";
var maxLen = Math.max(d1.length, d2.length);
var m = Math.pow(10, maxLen);
var result = Number(((arg1 * m + arg2 * m) / m).toFixed(maxLen));
var d = arguments[2];
return typeof d === "number" ? Number((result).toFixed(d)) : result;
},

Sub: function (arg1, arg2) {
return Calc.Add(arg1, -Number(arg2), arguments[2]);
},

Mul: function (arg1, arg2) {
var r1 = arg1.toString(), r2 = arg2.toString(), m, resultVal, d = arguments[2];
m = (r1.split(".")[1] ? r1.split(".")[1].length : 0) + (r2.split(".")[1] ? r2.split(".")[1].length : 0);
resultVal = Number(r1.replace(".", "")) * Number(r2.replace(".", "")) / Math.pow(10, m);
return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)));
},

Div: function (arg1, arg2) {
var r1 = arg1.toString(), r2 = arg2.toString(), m, resultVal, d = arguments[2];
m = (r2.split(".")[1] ? r2.split(".")[1].length : 0) - (r1.split(".")[1] ? r1.split(".")[1].length : 0);
resultVal = Number(r1.replace(".", "")) / Number(r2.replace(".", "")) * Math.pow(10, m);
return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)));
},

FormatNumber: function formatNumber(num,cent,isThousand){
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))//检查传入数值为数值类型.
num = "0";
if(isNaN(cent))//确保传入小数位为数值型数值.
cent = 0;
cent = parseInt(cent);
cent = Math.abs(cent);//求出小数位数,确保为正整数.
if(isNaN(isThousand))//确保传入是否需要千分位为数值类型.
isThousand = 0;
isThousand = parseInt(isThousand);
if(isThousand < 0)
isThousand = 0;
if(isThousand >=1) //确保传入的数值只为0或1
isThousand = 1;
sign = (num == (num = Math.abs(num)));//获取符号(正/负数)
//Math.floor:返回小于等于其数值参数的最大整数
num = Math.floor(num*Math.pow(10,cent)+0.50000000001);//把指定的小数位先转换成整数.多余的小数位四舍五入.
cents = num%Math.pow(10,cent); //求出小数位数值.
num = Math.floor(num/Math.pow(10,cent)).toString();//求出整数位数值.
cents = cents.toString();//把小数位转换成字符串,以便求小数位长度.
while(cents.length<cent){//补足小数位到指定的位数.
cents = "0" + cents;
}
if(isThousand == 0) //不需要千分位符.
return (((sign)?'':'-') + num + '.' + cents);
//对整数部分进行千分位格式化.
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + num + '.' + cents);
}
};
window.Calc = calc;
}());

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章