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
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
Share Improve this question edited Feb 18, 2015 at 7:41 bmp asked Feb 18, 2015 at 7:32 bmpbmp 211 silver badge3 bronze badges 4- provide some inputs along with expected outputs. – Avinash Raj Commented Feb 18, 2015 at 7:33
- What about adding this in front of your regex? (-|) It will match a minus or nothing. – ByteHamster Commented Feb 18, 2015 at 7:42
- 1 Do you need to use a RegEx? There are better ways in JS to validate numbers – thomaux Commented Feb 18, 2015 at 7:50
- Please find the answers below and mark one as accepted that best solves your problem. – Rahul Desai Commented Feb 18, 2015 at 9:15
5 Answers
Reset to default 5Here 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+)?$/
Source
Use this regex:
(?!=\A|\s)(-|)[\d^]*\.[\d]*(?=\s|\z)
It will match all floating point numbers. Demo: https://regex101./r/lE3gV5/2
Try the following,
str.replace(/-?[0-9]+(\.[0-9]+)?/g,'')
OR
str.match(/^-?[0-9]+(?:\.[0-9]+)?$/,'')
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]);
}
You can try to use regexp:
/-?(\d+\.\d+)[^\w\.]/g
DEMO