[jquery] jQuery get text as number

This code doesn't work:

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

HTML:

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

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

What is the solution?

This question is related to jquery variables

The answer is


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());

number = parseInt(number);

That should do the trick.


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
}