JS 数字 货币格式化 保留两位小数

如图:
在这里插入图片描述
js函数:

/**
* 将数值四舍五入(保留2位小数)后格式化成金额形式
*
* @param num 数值(Number或者String)
* @return 金额格式的字符串,如'1,234,567.45'
* @type String
*/
function formatCurrency(num) {
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num)){
			num = "0";
		}
		
		sign = (num == (num = Math.abs(num)));//数字是否为正负数  Math.abs() 返回参数的绝对值
		num = Math.floor(num*100+0.50000000001);//返回小于等于num*100+0.50000000001的最大整数:
		cents = num%100; //小数位数
		num = Math.floor(num/100).toString();//整数位数
		if(cents<10){
			cents = "0" + cents;//小数位补0
		}
		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);
}

/**
* 将数值四舍五入(保留1位小数)后格式化成金额形式
*
* @param num 数值(Number或者String)
* @return 金额格式的字符串,如'1,234,567.4'
* @type String
*/
function formatCurrencyTenThou(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)){
		num = "0";
	}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*10+0.50000000001);
	cents = num%10;
	num = Math.floor(num/10).toString();
	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);
}

原文链接:JS对数字进行货币格式化并且保留两位小数点,小数用0补全

你可能感兴趣的:(前端,JavaScript)