views:

51

answers:

5

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?

+4  A: 

myInteger = parseInt(myString);

It's a standard javascript function.

Trimack
+1  A: 
var number = parseInt($(this).find('.number').text());
var current = 600;
if (current > number)
{
     // do something
}
MrThys
+1  A: 
number = parseInt(number);

That should do the trick.

Nilks
+3  A: 

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.

Matt
+2  A: 

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());
RoToRa
`+` won't return zero for an invalid number, it will return `NaN`. IMO, this makes it more ideal than *parseInt()*, because *parseInt* will attempt to find a number at the start of a malformed string which can result in confusion (e.g. 1,000 becomes 1). `+str` is the same as writing `Number(str)`.
Andy E
Doh, you are right.
RoToRa