在JavaScript中验证十进制数字最干净、最有效的方法是什么?
奖励积分:
清晰解决方案应干净简单。跨平台。
测试用例:
01. IsNumeric('-1') => true
02. IsNumeric('-1.5') => true
03. IsNumeric('0') => true
04. IsNumeric('0.42') => true
05. IsNumeric('.42') => true
06. IsNumeric('99,999') => false
07. IsNumeric('0x89f') => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3') => false
10. IsNumeric('') => false
11. IsNumeric('blah') => false
$('.rsval').bind('keypress', function(e){
var asciiCodeOfNumbers = [48,46, 49, 50, 51, 52, 53, 54, 54, 55, 56, 57];
var keynum = (!window.event) ? e.which : e.keyCode;
var splitn = this.value.split(".");
var decimal = splitn.length;
var precision = splitn[1];
if(decimal == 2 && precision.length >= 2 ) { console.log(precision , 'e'); e.preventDefault(); }
if( keynum == 46 ){
if(decimal > 2) { e.preventDefault(); }
}
if ($.inArray(keynum, asciiCodeOfNumbers) == -1)
e.preventDefault();
});