/**
* Returns the N-th digit of a number counting from the left.
*
* Examples:
* getNthDigitFromLeft(12345, 1) === 1
* getNthDigitFromLeft(12345, 3) === 3
*
* @param inputNumber The number to extract the digit from.
* @param digitPosition The digit position (1-based, from the left).
* @returns The digit at the specified position.
* @throws RangeError If digitPosition is out of range.
*/
function getNthDigitFromLeft(
inputNumber: number,
digitPosition: number
): number {
const digitString: string = Math.abs(inputNumber).toString();
if (
!Number.isInteger(digitPosition) ||
digitPosition < 1 ||
digitPosition > digitString.length
) {
throw new RangeError(
"Digit position is out of range."
);
}
return Number(digitString[digitPosition - 1]);
}
// usage
const accountNumber: number = 987654321;
const fourthDigitFromLeft: number = getNthDigitFromLeft(accountNumber, 4);
console.log(getNthDigitFromLeft(accountNumber, 4));
/*
run:
6
*/