2

I know that we can extract an integer value from a string using

var x = "> 1";
x = parseInt(x.match(/\d+/)[0], 10));

How do I get a float value from a string

example: var x = "> 1.1"

I know we can just use x.substring(2);

But for a more generic solution? since the above will not give the accurate result for

var x = "1.1"

So what is the best way to extract the float value 1.1 from

var x = "> 1.1"
1
  • 1
    How about /\d+\.?\d*/ Commented Feb 7, 2014 at 18:18

4 Answers 4

5

Use parseFloat and a regular expression that matches a number with optional decimals and minus sign.

var f = parseFloat(x.match(/-?(?:\d+(?:\.\d*)?|\.\d+)/)[0]);
Sign up to request clarification or add additional context in comments.

Comments

2

You can try the following one to extract only numbers like floating or integer as an array as many as you want using the match function.

str = 'On schedule: 3243.8 miles away (4491 minutes)';
values = str.match(/[0-9.]+/g); //=> ["3243.8", "4491"]

Comments

1
x = parseFloat(x.match(/[-+]?([0-9]*\.[0-9]+|[0-9]+)/));

2 Comments

Please explain your solution so that future visitors to this question will understand how it solves the problem at hand.
The argument matches a number with an optional + or - sign followed by at least one digit followed by an optional decimal point with at least one digit following the decimal point.
0

Use parseFloat(). It does exactly what you're looking for.

1 Comment

It won't skip over the > at the beginning.

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.