这是另一种无需担心溢出的解决方案(您可以在此处找到演示
$(document).ready(function(){
$('#txtInput').keydown(function(e){
var value = $('#txtInput').val().toString();
var number = null;
if(value == '')
value = '0.00';
switch(e.which)
{
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
number = e.which - 48;
case 8:
case 46:
case 32:
case 37:
case 38:
case 39:
case 40:
break;
default:
e.preventDefault();
break;
}
var dotIndex = value.indexOf('.');
if(number === null)
{
value = value.substr(0,dotIndex-1) + '.' + value.substr(dotIndex -1,1) + value.substr(dotIndex+1,1);
if(value.indexOf('.') ==0)
{
value = '0' + value;
}
}
else
{
value = value.substr(0,dotIndex) + value.substr(dotIndex+1,1) + '.' + value.substr(dotIndex+2);
value += number.toString();
value = value.replace(/^0+/,'');
if(value.indexOf('.') == 0)
{
value = '0' + value;
}
}
$('#txtInput').val(value);
e.preventDefault();
}).keyup(function(e){
switch(e.which)
{
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
e.preventDefault();
break;
}
});
});
和这段代码的 html
<input type='text' id='txtInput' />