The simplest way to convert a string into a number is to use either parseInt or the + unary operator.
Code: Select all
var cssPxValue = element.style.marginTop;
parseInt(cssPxValue); //converts cssPxValue to an number
//or
(+cssPxValue); //faster than parseInt
This will convert strings that at least start with a number ("123abc", "11px", etc), but for strings that do not start with a number character or even contain them ("abc123", "auto", etc) both parseInt and the + operator return NaN. Sense in a css property there can be things like "auto", I want to know of a way to convert strings to numbers
always; 0 rather than NaN.
The current way I have to do this is:
Code: Select all
(+cssPxValue.replace(/\D*/g, ""));
But through my testing have found that adding the replace method causes the operation to be drastically slower than without it (going from 0.004ms up to 3.544ms). For what I'm using this for, performance is #1 and these little numbers add up big time. So, I need a solution that is close to the speed of the basic conversion, but does convert all strings to a number and not NaN.
Thanks for reading. Any thoughts on this?
EDIT: I found a faster and more reliable solution, but still "slower":
Code: Select all
fuction toNumber(s) {
return +s.replace(/[^\d\.]*/g, '');
}