Link to home
Start Free TrialLog in
Avatar of DesertWarrior
DesertWarrior

asked on

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
SOLUTION
Avatar of Zyloch
Zyloch
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of VincentPuglia
VincentPuglia

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

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

Vinny

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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;
alert(res1)
</script>



<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>