js对金额的完美处理
<INPUT TYPE="text" style="ime-mode:disabled" onkeydown="if(event.repeat)event.returnValue=false;//屏蔽连按" onkeypress="initPrice(this)" onblur="checkinp(this)">
<SCRIPT LANGUAGE="JavaScript">
<!--
function initPrice(oInput){
var num = oInput.value;
/* 取光标位置 */
var s = document.selection.createRange();
var r = oInput.createTextRange();
s.setEndPoint( "StartToStart",r);
var curP = s.text.length;
num = num.substring(0,curP) + String.fromCharCode(event.keyCode) + num.substring(curP);
var reg = /^\-?([\d\,]*\.?\d{0,3}?)?$/;
// 0~9:48~57; \,:44; \-:45; \.:46;
if ( event.keyCode<44 || event.keyCode>57 || event.keyCode==47 || !reg.test(num) ) {
if (event.keyCode==46) curP = num.indexOf(".")+1;
event.returnValue = false;
}
else {
curP += 1;
if (num=="-") return;
if (/\.\d{3}$/.test(num)) num = num.substring(0,num.length-1);
event.returnValue = false;
num = num.replace(/,/g,"");
num = parseFloat(num).toFixed(2);
var re = /(-?\d+)(\d{3})/;
while(re.test(num)){
num = num.replace(re,"$1,$2")
}
oInput.value=num;
if(num.indexOf(".")>0 && curP <= num.indexOf(".") ) curP = num.indexOf(".");
}
//恢复光标位置
r.moveStart( 'character',curP);
r.collapse(true);
r.select();
}
function checkinp(obj){
var num = obj.value.replace(/,/g,"");
num = parseFloat(num).toFixed(2);
var re = /(-?\d+)(\d{3})/;
while(re.test(num)){
num = num.replace(re,"$1,$2")
}
obj.value=num;
}
//-->
</SCRIPT>