regular expression for floating point value

2019-08-28 20:55发布

I want my textbox to have only floating point value, and filter out any symbols and alphabetical letters, the nearest solution i found is:

jQuery(".sow-items .discovery_repeat input.hours").live("keyup", function(e) {       
    $(this).val($(this).val().replace(/[^\d]/, ''));       
});

but it also filters out decimal point. how to exclude decimal from the above filter or any new suggestions?

4条回答
我想做一个坏孩纸
2楼-- · 2019-08-28 20:55

Try this:

jQuery(".sow-items .discovery_repeat input.hours").live("keyup", function(e) {       
    $(this).val($(this).val().replace(/[^\d.]/g, ''));       
});
查看更多
再贱就再见
3楼-- · 2019-08-28 21:10

/\b[-+]?[0-9]*\.?[0-9]+\b/g or /^[-+]?[0-9]*\.?[0-9]+$/ should do the trick, unless you want to allow numbers like "1.4E-15" in there.

http://www.regular-expressions.info/floatingpoint.html has some suggestions for that unusual case.

查看更多
4楼-- · 2019-08-28 21:13

You need to match either non digit or non dot and the dot needs to be escaped

jQuery(".sow-items .discovery_repeat input.hours").live("keyup", function(e) {       
    $(this).val($(this).val().replace(/[^\d]|[^\.]/, ''));       
});
查看更多
贪生不怕死
5楼-- · 2019-08-28 21:20
jQuery(".sow-items .discovery_repeat input.hours").live("keyup", function(e) {   
    var newVal = $(this).val().replace(/[^\d.]/, '').split(".");
    if ( newVal.length>2 ) newVal.length = 2; newVal.join("."); 
    $(this).val(newVal);       
});

@Dave Newton: Only one . ..

查看更多
登录 后发表回答