tags:

views:

42

answers:

3

so I'm wanting to do something like this:

I've got a variable that will return anything upto a 7 didget number, and i need to test the value of each digit individually. I can only think to do it as a string, but please feel free to offer help as a string or an integer.

total = "1658793";
parseFloat(total.substring(6)) == 3;

returns "true"

but I need to be able to get the next value, and the next, and then next, individually.

and obviously

parseFloat(total.substring(5)) == 9;

returns "false"

as "parseFloat(total.substring(5)) = 93" but i need to be able to regex check or something to find the 9 on its own. i need the 9, not the 93 does that make sense??

thanks Matt.

A: 

You could use the string split() method

var arr = total.split('');

then

var cnt = arr.length;
for(var i = 0; i < cnt; i++)
{
    if(parseInt(arr[i]) == 5)
    {
        // do something here
    }
}

or you could %10 then divide by 10 (integer division)

while(total > 0)
{
    var digit = total % 10;
    total = Math.floor(total / 10);
    if(digit == 5) 
    {
        // do something here
    }
}
John Boker
+1  A: 

Use

parseFloat(total.substring(5, 6)) == 9;
parseFloat(total.substring(4, 5)) == 7;

... And so on

Vinodh Ramasubramanian
A: 

Just parse the entire starting number into an integer and examine its digits using the modulus (%) operator.

var num = parseInt(total, 10);
var ones = num % 10;
if (ones != 3) { ... }
num = (num - ones) / 10;
var tens = num % 10;
if (tens != 9) { ... }
num = (num - tens) / 10;
var hundreds = num % 10;

...And so on.

Sean