例 1 , 使数字 1111111 变成 11,111,111.00 保留两位小数。 保留两位小数。
复制代码代码如下:
<html>
<Evista>
<script type = "text/javaScript">
function outputMoney (número) {
número = número.replace (//,/g, "");
if (isnan (número) || número == "") return "";
número = math.round (número * 100) / 100;
if (número <0)
return ' -' + outputDollars (math.floor (math.abs (número) - 0) + '' ') + salidas (math.abs (número) - 0);
demás
return outputDollars (math.floor (número - 0) + '' ') + outputCents (número - 0);
}
// 格式化金额
Función OutputDollars (número) {
if (number.length <= 3)
return (número == ''? '0': número);
demás {
var mod = número.length % 3;
var sotado = (mod == 0? '': (number.substring (0, mod)));
para (i = 0; i <math.floor (número.length / 3); i ++) {
if ((mod == 0) && (i == 0))
salida + = número.substring (mod + 3 * i, mod + 3 * i + 3);
demás
salida + = ',' + number.substring (mod + 3 * i, mod + 3 * i + 3);
}
return (salida);
}
}
function outpleCents (cantidad) {
cantidad = math.round (((cantidad) - Math.floor (cantidad)) * 100);
devolución (cantidad <10? '.0' + Cantidad: '.' + Cantidad);
}
</script>
</ablo>
<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 Transitional // en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transicional.dtd ">
<html xmlns = "http://www.w3.org/1999/xhtml">
<Evista>
<meta http-equiv = "content-type" content = "text /html; charset = gb2312" />
<title> js 格式化金额的代码 --- www.vevb.com </title>
<script language = "javaScript">
función tran (id)
{
var v, j, sj, rv = "";
v = id.value.replace (/,/g, ""). Split (".");
J = V [0]. Length % 3;
sj = v [0] .substr (j) .ToString ();
para (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] == Undefined)? 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;
}
función tran2 (id)
{
var v;
v = id.value.replace (/,/g, "");
alerta (v);
}
</script>
<style type = "text/css">
<!-
cuerpo, td, th, entrada {
tamaño de fuente: 12px;
}
->
</style> </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 需刷新才能执行]