I am using this regex to allow floating point numbers
str.replace(/(\.\d\d)\d+|([\d.]*)[^\d.]/, '$1$2')
I need to allow negative numbers also. Any ideas.
This allows 123.45 and it wont allow the chars like 123.45a. I need to allow -123.45. Currently its not allowing me to enter negative numbers
Here is a shorter regex that matches negative floats:
/^-?[0-9]\d*(\.\d+)?$/
Explaination and demo of this regex
If you want to match explicitly positive numbers like +123.123
along with the negative ones, use the following regex:
/^[-+]?[0-9]\d*(\.\d+)?$/
Use this regex:
(?!=\A|\s)(-|)[\d^]*\.[\d]*(?=\s|\z)
It will match all floating point numbers. Demo: https://regex101.com/r/lE3gV5/2
You can try this Regex:
parseFloat(str.replace(/.*?(\-?)(\d*\.\d+)[^\d\.]*/, '$1$2'));
But its better to match the number than replace the other characters:
var matches = /(\-?\d*\.(?:\d+)?)/.exec(str);
if (typeof matches != 'undefined' && matches.length > 0) {
var num = parseFloat(matches[1]);
}
Try the following,
str.replace(/-?[0-9]+(\.[0-9]+)?/g,'')
OR
str.match(/^-?[0-9]+(?:\.[0-9]+)?$/,'')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.