Sid Gabski
Sid Gabski

Reputation: 9

How to output a number with a certain digit in a certain place in javascript

Thinking it would be like

for number from range x,y if number in ones or number in hundreds print else

??? I don't know what command to do the if statement.

Upvotes: 0

Views: 66

Answers (4)

Raphael Castro
Raphael Castro

Reputation: 1148

your question is super ambiguous, please be more specific. That being said this function should do what you are asking.

function printIfDigitIsInPlace(INPUT, DIGIT, PLACE) {
    const arr = Array.from(INPUT.toString());
    if (arr[PLACE] === DIGIT.toString()) console.log(INPUT);
}

Upvotes: 0

Sash Sinha
Sash Sinha

Reputation: 22370

You could store the tensDigit and onesDigit in variables and then check them in the if statement for better readabilty:

for (let num = 100; num <= 200; num++) {
    const tensDigit = Math.floor((num % 100) / 10);
    const onesDigit = num % 10;
    if (tensDigit === 3 || onesDigit === 2) {
        console.log(num);
    }
}

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

You may try using the modulus operator here:

for (i=100; i <= 200; ++i) {
    if (i % 10 == 2 || Math.floor(i / 10) % 10 == 3) {
        console.log(i);
    }
    else {
        // turned this off for demo purposes
        // console.log("???");
    }
}

Upvotes: 1

michael
michael

Reputation: 4173

for (let i = 100; i <= 200; i++) {
    if (i % 10 === 2 || (i / 10) % 10 === 3) {
        // do something
    } else {
        console.log('???')
    }
}

Upvotes: 0

Related Questions