最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - JavaScript: How to convert an HTML string into a JavaScript number? - Stack Overflow

programmeradmin0浏览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.

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.

Share Improve this question edited Sep 14, 2011 at 15:05 Andrew asked Sep 13, 2011 at 22:37 AndrewAndrew 239k195 gold badges531 silver badges718 bronze badges
Add a ment  | 

3 Answers 3

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

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 mas, 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)

  1. 暂无评论