例 1 , 使数字 1111111 变成 11.111.111.00 , 保留两位小数。
复制代码代码如下:
<Html>
<head>
<type skrip = "Teks/JavaScript">
fungsi outputmoney (angka) {
angka = number.replace (//,/g, "");
if (isnan (angka) || angka == "") return "";
angka = math.round (angka * 100) / 100;
if (angka <0)
return ' -' + outputDollars (math.floor (math.abs (angka) - 0) + '') + outputcents (math.abs (angka) - 0);
kalau tidak
return outputDollars (math.floor (angka - 0) + '') + outputcents (angka - 0);
}
// 格式化金额
fungsi outputDollars (angka) {
if (number.length <= 3)
return (number == ''? '0': number);
kalau tidak {
var mod = number.length % 3;
var output = (mod == 0? '': (number.substring (0, mod)));
untuk (i = 0; i <math.floor (number.length / 3); i ++) {
if ((mod == 0) && (i == 0))
output + = number.substring (mod + 3 * i, mod + 3 * i + 3);
kalau tidak
output + = ',' + number.substring (mod + 3 * i, mod + 3 * i + 3);
}
return (output);
}
}
fungsi outputcents (jumlah) {
Jumlah = Math.round (((Jumlah) - Math.floor (Jumlah)) * 100);
pengembalian (jumlah <10? '.0' + Jumlah: '.' + Jumlah);
}
</script>
</head>
<body>
<input type = text maxlength = "8" id = "test" oNblur = "this.value = outputMoney (this.value);" >
</body>
</html>
[Ctrl+a 全选 注: 如需引入外部 js 需刷新才能执行]
例 2 , 使数字 1111111 变成 11.111.111 --- 和使 11.111.111 变成 1111111 --- 整数-
复制代码代码如下:
<! Doctype html public "-// w3c // dtd xhtml 1.0 transisi // en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv = "konten-tipe" content = "text /html; charset = gb2312" />
<title> js 格式化金额的代码 --- www.vevb.com </title>
<bahasa skrip = "javascript">
function tran (id)
{
var v, j, sj, rv = "";
v = id.value.replace (/,/g, ""). split (".");
j = v [0] .length % 3;
sj = v [0] .substr (j) .toString ();
untuk (var i = 0; i <sj.length; i ++)
{
rv = (i % 3 == 0)? rv + "," + sj.substr (i, 1): rv + sj.substr (i, 1);
}
var rvalue = (v [1] == tidak terdefinisi)? v [0] .substr (0, j) + rv: v [0] .substr (0, j) + rv + "." + V [1];
if (rvalue.charcodeat (0) == 44)
{
rvalue = rvalue.substr (1);
}
id.value = rValue;
}
fungsi tran2 (id)
{
var V;
v = id.value.replace (/,/g, "");
waspada (v);
}
</script>
<type style = "text/css">
<!-
tubuh, td, th, input {
font-size: 12px;
}
->
</tyle> </head>
<body>
<input name = "tt" type = "text" id = "tt" size = "80" onkeyup = "tran (this)" />
<br/>
<input name = "tt" type = "text" id = "tt2" size = "80" onkeyup = "tran2 (this)" />
</body>
</html>
运行测试 :
[Ctrl+a 全选 注: 如需引入外部 js 需刷新才能执行]