开发者

jQuery get text as number

开发者 https://www.devze.com 2023-01-12 12:58 出处:网络
This code doesn\'t work: var number = $(this).find(\'.number\').text(); var current = 600; if (current > number){

This code doesn't work:

var number = $(this).find('.number').text();
var current = 600;
if (current > number){
     // do something
}

H开发者_StackOverflow中文版TML:

<div class="number">400</div>

Seems there is some problem with converting text() from text-like value to number.

What is the solution?


Always use parseInt with a radix (base) as the second parameter, or you will get unexpected results:

var number = parseInt($(this).find('.number').text(), 10);

A popular variation however is to use + as a unitary operator. This will always convert with base 10 and never throw an error, just return zero NaN which can be tested with the function isNaN() if it's an invalid number:

var number = +($(this).find('.number').text());


myInteger = parseInt(myString);

It's a standard javascript function.


Use the javascript parseInt method (http://www.w3schools.com/jsref/jsref_parseint.asp)

var number = parseInt($(this).find('.number').text(), 10);
var current = 600;
if (current > number){
     // do something
}

Don't forget to specify the radix value of 10 which tells parseInt that it's in base 10.


If anyone came here trying to do this with a decimal like me:

myFloat = parseFloat(myString);

If you just need an Int, that's well covered in the other answers.


var number = parseInt($(this).find('.number').text());
var current = 600;
if (current > number)
{
     // do something
}


number = parseInt(number);

That should do the trick.

0

精彩评论

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