1

How to convert a number with prefix into double/float e.g. STA01.02to 1.02?

3 Answers 3

3

Use regex to strip the non-numbers (excluding ".") for a more flexible solution:

parseFloat("STA01.02".replace(/[^0-9\.]+/g, ''));
Sign up to request clarification or add additional context in comments.

1 Comment

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.)
0
// 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

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" ?
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.
0

If the prefix always the same...

var str = "STA01.02";
var number = parseFloat(str.substring(3));

1 Comment

"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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.