How to get the Nth digit of a number in JavaScript

1 Answer

0 votes
/**
 * Returns the N-th digit of a number counting from the left.
 *
 * Examples:
 * getDigitFromLeft(12345, 1) === 1
 * getDigitFromLeft(12745, 3) === 7
 *
 * @param {number} number - The input integer.
 * @param {number} position - The digit position (1-based, from the left).
 * @returns {number} The digit at the specified position.
 * @throws {RangeError} If position is out of range.
 */
function getDigitFromLeft(number, position) {
    const digits = Math.abs(number).toString();

    if (
        !Number.isInteger(position) ||
        position < 1 ||
        position > digits.length
    ) {
        throw new RangeError("Position is out of range.");
    }

    return Number(digits[position - 1]);
}

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


/*
run:

1
7

*/

 



answered Oct 13 by avibootz
...