How to convert a number with prefix into double/float e.g. STA01.02to 1.02?
3 Answers
Use regex to strip the non-numbers (excluding ".") for a more flexible solution:
parseFloat("STA01.02".replace(/[^0-9\.]+/g, ''));
1 Comment
nnnnnn
Or just
/[^\d.]/g - you don't need to escape the . within the [], and you don't need the +. (Although perhaps with the + is more efficient because it would only do a single replacement? Not sure.)// Assumed "STA0" is the fixed-length prefix, you can adjust the substring at the start you're getting rid of.
var myString = "STA01.02";
var noPrefix = myString.substring(4); // Just "1.02"
var myNumber = parseFloat(noPrefix);
console.log(myNumber); // Prints 1.02
2 Comments
Marielle
Hi! The letter prefix are fixed but the number portion changes (e.g. STA01.02, STA11.03, STA23.11) so I need the "01.02" portion... will the parsing still work if there is a "0" before the "1.02" ?
Brian Stinar
Oh, if you only want to get rid of "STA" and not "STAn" where n is a number, then it's var noPrefix = myString.substring(3); // Just "01.02". Or, if you want to get rid of all letters, use the accepted solution.
If the prefix always the same...
var str = "STA01.02";
var number = parseFloat(str.substring(3));
1 Comment
Brian Stinar
"A01.02" is given for substring(2) for this example. You need substring 3 for "01.02" or substring(4) for "1.02". substring(2) won't parseFloat correctly.