Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery convert integer to string and back

These are the logical steps which I need to do with jquery:

x is a 2 digit number(integer) derived from an input.value();

If  var x is **not** 33 or 44
    Convert this 2 digit number to string;
    split the string in 2 parts as number;
    Add these 2 values until they reduce to single digit;
    Return var x value as this value;
Else
    Return var x value literally as 33 or 44 whatever is the case;

Thanks!

like image 234
Richbyte Avatar asked Oct 14 '22 06:10

Richbyte


2 Answers

if (x != 33 && x != 44) {
    while (x > 9) {
        var parts = ('' + x).split('');
        x = parseInt(parts[0]) + parseInt(parts[1]);
    }
    return x;
} else {
    return x;
}    

Works only if the input is really max 2 digits long as you say, else you'll need to add the numbers in a for loop over parts.length. E.g.:

if (x != 33 && x != 44) {
    while (x > 9) {
        var parts = ('' + x).split('');
        for (var x = 0, i = 0; i < parts.length; i++) {
            x += parseInt(parts[i]);
        }
    }
    return x;
} else {
    return x;
}    
like image 113
BalusC Avatar answered Oct 19 '22 22:10

BalusC


I'd try:

function process (x) {
    if ((x != 33) && (x != 44)) {
        while (x > 9) {
            x = Math.floor (x / 10) + (x % 10);
        }
    }
    return x;
}

I see little reason to convert it to a string when you can use arithmetic operations.

like image 32
paxdiablo Avatar answered Oct 20 '22 00:10

paxdiablo