Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regex and negative numbers

Status
Not open for further replies.

simon551

IS-IT--Management
May 4, 2005
249
I found this code somewhere that helps me handle formatted numbers on an input. I would like to modify it so it will accept negative numbers (and not convert them to positive)

Code:
function convertToDouble(v){
	var str = Number(v.replace(/[^0-9\.]+/g,""));
	num= (parseFloat(str));
	return num;
}
 
I think I figured it out. This worked:
var str = Number(v.replace(/[^-0-9\.]+/g,""));
 
/-*[^0-9\.]+/

_________________
Bob Rashkin
 
You're right. Mine won't work.

_________________
Bob Rashkin
 
From the name of the function, the approach seems frightenly "wrong"! unless the input v is of a very special pattern only.

This is a suggestion of how these things can be made working more generally. And it becomes more involved.
[tt]
//this function accepts exotic +-+----123.456 etc
//it excludes only integral part be absent like .123.
function extract_num(v) {
var rx=/(-|\+)*\d+\.?\d*/g;
var a=v.match(rx);
return a; //return null of Array type
}

var s="abc12.4pqr--123.56xyz++-14";
var w=extract_num(s);
if (w instanceof Array) {
for (var i=0; i<w.length; i++) {
alert(eval(w.replace(/\+|-/g,RegExp.$1+"1*")));
}
} else {
alert ('no valid number is extracted.');
}
[/tt]
The odd look and the use of eval() is to make exotic case like -- or +- etc work out as valid numbers; and that such as --123.00 will provoke NaN for parseFloat(). Seemingly not very attractive, but functionally it is forced by the necessity.
 
further notes
The function also ill behaves when there is a sequence of number like 123.456.789. It will take up 123.456 and leave out 789. But in retrospect, how to interprete 123.456.789?!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top