我有一个输入字段,我想限制,以便用户只能输入一个最多两位小数的数字.想用jQuery做到这一点.
我可以以某种方式使用jQuery toFixed()函数吗?
感谢名单!
$('input#decimal').blur(function(){
var num = parseFloat($(this).val());
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);
if(num/cleanNum < 1){
$('#error').text('Please enter only 2 decimal places, we have truncated extra points');
}
});
Run Code Online (Sandbox Code Playgroud)
这是一个小提琴http://jsfiddle.net/sabithpocker/PD2nV/
使用toFixed
将无论如何导致近似123.6666 -> 123.67
如果你想避免近似检查这个答案显示两个小数位,没有舍入
小智 6
使用正则表达式的替代方法:
$('#id').on('input', function () {
this.value = this.value.match(/^\d+\.?\d{0,2}/);
});
Run Code Online (Sandbox Code Playgroud)
id选择器可以由css选择器替换.
归档时间: |
|
查看次数: |
37347 次 |
最近记录: |