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

I have a number that I need to pull from my html:<span>123,456.78<span>How can I convert t

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743659133a4485891.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信