x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 655

# looking for a similar function as parseInt

Hi
What function other than parseInt transforms a string into an integer? I'm using parseInt but It doesn't work with values like 1.#QNAN
I'm looking for a function that will transform anything that is not an integer into a 0 (zero)

thanks
0
DesertWarrior
2 Solutions

Commented:
Hi

Basically, you just use parseInt (or parseFloat) and then check if the resulting value isNaN or not:

function getInt(int,base) {
base=(base) ? parseInt(base,10) : 10;
if (isNaN(base)) {
base=10;
}
int=parseInt(int,base);
if (isNaN(int)) {
return(0);
} else {
return(int);
}
}

Regards,
Zyloch
0

Commented:
if you simply want to assign a 0 to '1.#QNAN' :

var theVal = isNaN(num) ? 0 : num;

Vinny

0

Commented:
Actually, as long as the argument to parseInt begins with a numeric character, parseInt will return an integer.  For example, parseInt('1.#QNAN') == 1.  (See http://msdn.microsoft.com/library/en-us/script56/html/js56jsmthparseint.asp.)

You could, however, do something like

function TransToInt(strVal) {
if(!strVal)
return 0;
var intVal = parseInt(strVal);
if(isNaN(intVal)  ||  '' + intVal != strVal)
return 0;
else
return intVal;
}
0

Systems architectCommented:
The best conversion from String to Number is by multiplicate by one. It converts eben empty string directly to zero.

Here an example:
<script>
var myNum1 = "1.#QNAN";
var res1 = myNum1*1;
if(isNaN(res1)) res1=0;
</script>

0

Commented:
<script>
var x = 'asdf';
var i = isNaN(parseInt(x))?0:parseInt(x);
</script>

if you want to convert stuff like '1asdf' into 1, try this:

<script>
var x = '1asdf';
var i = parseInt(x.replace(/[^0-9]+/ig,''));
i=isNaN(i)?0:i;
</script>
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.