例 1 , 使数字 1111111 变成 11.111.111.00 , 保留两位小数。
复制代码代码如下:
<html>
<head>
<script type = "text/javascript">
função outputMoney (número) {
número = número.Place (//,/g, "");
if (isnan (número) || número == "") retornar "";
número = math.Round (número * 100) / 100;
se (número <0)
return ' -' + outputDollars (math.floor (math.abs (número) - 0) + '') + outputCents (math.abs (número) - 0);
outro
Retorno outputDollars (Math.floor (número - 0) + '') + outputCents (número - 0);
}
// 格式化金额
função outputDollars (número) {
if (número.length <= 3)
return (número == ''? '0': número);
outro {
var mod = número.Length % 3;
var output = (mod == 0? '': (número.substring (0, mod)));
for (i = 0; i <math.floor (número.Length / 3); i ++) {
if ((mod == 0) && (i == 0))
saída + = número.substring (mod + 3 * i, mod + 3 * i + 3);
outro
saída + = ',' + número.substring (mod + 3 * i, mod + 3 * i + 3);
}
return (saída);
}
}
função outputCents (valor) {
valor = math.ound (((quantidade) - math.floor (valor)) * 100);
retorno (quantidade <10? '.0' + quantidade: '.' + quantidade);
}
</script>
</head>
<Body>
<Tipo de entrada = Texto maxLength = "8" id = "teste" 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 // pt" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-bransitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv = "content-type" content = "text /html; charset = gb2312" />
<title> JS 格式化金额的代码 --- www.vevb.com </ititle>
<Script Language = "JavaScript">
função Tran (id)
{
var v, j, sj, rv = "";
v = id.value.replace (/,/g, ""). split (".");
J = V [0] .Length % 3;
sj = v [0] .substr (j) .toString ();
for (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] == indefinido)? 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;
}
Função TRAN2 (ID)
{
var V;
v = id.value.replace (/,/g, "");
alerta (v);
}
</script>
<style type = "text/css">
<!-
corpo, td, th, entrada {
tamanho de fonte: 12px;
}
->
</style> </head>
<Body>
<nome de entrada = "tt" type = "text" id = "tt" size = "80" onkeyup = "tran (this)" />
<br/>
<nome de entrada = "tt" type = "text" id = "tt2" size = "80" onkeyup = "TRAN2 (this)" />
</body>
</html>
运行测试
[Ctrl+A 全选 注: 如需引入外部 JS 需刷新才能执行]