0

I have a number that I need to pull from my html:

<span>123,456.78</span>

How can I convert this string into a number that I can do math on?

var numberString = $('span').text();
var realNumber = Number(numberString); //returns NaN

A jQuery-only solution would be okay.

3 Answers 3

7

parseInt() or parseFloat() would just about do it.

var number = parseFloat($('span').text());

after checking and seeing this doesn't work...

try

var number = $('span').text().replace(/([^0-9\.])/g,"");

var number = parseFloat($('span').text().replace(/([^0-9\\.])/g,""));
Sign up to request clarification or add additional context in comments.

4 Comments

parseFloat("123,456.78") returns 123. That doesn't seem like a useful result to me.
this update will replace all none number and '.' characters. including '$' ',' and '¢'
@lonesomeday, yes.. i tested it after i posted it. see update.
@rlemon. You'd still need to call parseFloat in the second method to convert to a number
5

I'm not sure what realNumber does, but here's how I'd convert that string into a number:

var numberString = $('span').text();
var amount = + numberString.replace(/,/g, '');

This removes the commas, then uses the + unary operator to convert the string to a number. In your example, the result is the number 123456.78.

4 Comments

Good catch on the comma (although I'd still use parseFloat); upvoting yours too. Still deleting mine.
@Dave I prefer to use the unary operator because it returns NaN when it fails, rather than an incorrect number.
Oops! I just realized my code sample was wrong. I was trying to assign the number to a variable called "realNumber", not call a function.
Nice! - "unary plus is the fastest and preferred way of converting something into a number"
0

updated

var numberString = $('span').text();

var number = Number(numberString.replace(/[^0-9\.]+/g,""));

Comments

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.