例子,js格式化金额的代码。
//格式话金额
function fmoney(s, n)//将数字转换成逗号分隔的样式,保留两位小数s:value,n:小数位数
{
n = n > 0 && n <= 20 ? n : 2;
s = parsefloat((s + "").replace(/[^d.-]/g, "")).tofixed(n) + "";
var l = s.split(".")[0].split("").reverse(),
r = s.split(".")[1];
t = "";
for(i = 0; i < l.length; i ++ )
{
t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
}
return t.split("").reverse().join("") + "." + r;
}
//还原金额
function rmoney(s)
{
return parsefloat(s.replace(/[^d.-]/g, ""));
}
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)));
num = math.floor(num*100+0.50000000001);
cents = num%100;
num = math.floor(num/100).tostring();
if(cents<10)
cents = "0" + 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);
}
/**
* 将数值四舍五入(保留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);
}