How to get the Nth digit of a number from the right in JavaScript

2 Answers

0 votes
/**
 * Returns the N-th digit of a number counting from the right.
 *
 * Examples:
 * getDigitFromRight(12345, 1) === 5
 * getDigitFromRight(12345, 2) === 4
 * getDigitFromRight(12745, 3) === 7
 *
 * @param {number} number - The input integer.
 * @param {number} position - The digit position (1-based, from the right).
 * @returns {number} The digit at the specified position.
 * @throws {RangeError} If position is less than 1.
 */
function getDigitFromRight(number, position) {
    if (!Number.isInteger(position) || position < 1) {
        throw new RangeError("Position must be a positive integer.");
    }

    // Work with positive numbers only.
    const absoluteNumber = Math.abs(number);

    // Shift the desired digit to the ones place.
    const shiftedNumber =
        Math.floor(absoluteNumber / (10 ** (position - 1)));

    // Extract the last digit.
    return shiftedNumber % 10;
}

// Example usage
console.log(getDigitFromRight(12345, 1)); 
console.log(getDigitFromRight(12745, 3)); 
console.log(getDigitFromRight(12345, 5)); 


/*
run:

5
7
1

*/

 



answered Oct 13 by avibootz
0 votes
/**
 * Returns the N-th digit from the right (1-based).
 */
function getDigitFromRight(number, position) {
    if (!Number.isInteger(position) || position < 1) {
        throw new RangeError("Position must be a positive integer.");
    }

    return Math.floor(Math.abs(number) / (10 ** (position - 1))) % 10;
}

// Example usage
console.log(getDigitFromRight(12345, 1)); 
console.log(getDigitFromRight(12745, 3)); 
console.log(getDigitFromRight(12345, 5)); 


/*
run:

5
7
1

*/

 



answered Oct 13 by avibootz
...