开发者

JavaScript: How to convert an HTML string into a JavaScript number?

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(开发者_C百科numberString); //returns NaN

A jQuery-only solution would be okay.


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,""));


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.


updated

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜