/**
* Returns the Nth digit after the decimal point.
*
* Examples:
* getNthDecimalDigit(12.3456, 1) => 3
* getNthDecimalDigit(12.3456, 2) => 4
* getNthDecimalDigit(12.3456, 3) => 5
* getNthDecimalDigit(12.3456, 4) => 6
*
* @param {number} value - The number to inspect.
* @param {number} position - The digit position after the decimal point (1-based).
* @returns {number} The Nth digit, or 0 if it does not exist.
* @throws {TypeError} If arguments are invalid.
*/
function getNthDecimalDigit(value, position) {
// Validate inputs
if (!Number.isFinite(value)) {
throw new TypeError("value must be a finite number.");
}
if (!Number.isInteger(position) || position < 1) {
throw new TypeError("position must be a positive integer.");
}
// Convert to absolute value so negative numbers work correctly
const absValue = Math.abs(value);
// Shift the desired digit to the ones place
const shifted = absValue * Math.pow(10, position);
// Extract the digit
return Math.floor(shifted) % 10;
}
// -----------------------------------------------------------------------------
// Usage Examples
// -----------------------------------------------------------------------------
const number = 123.456789;
console.log(`Number: ${number}`);
console.log(`1st digit after decimal: ${getNthDecimalDigit(number, 1)}`);
console.log(`2nd digit after decimal: ${getNthDecimalDigit(number, 2)}`);
console.log(`3rd digit after decimal: ${getNthDecimalDigit(number, 3)}`);
console.log(`4th digit after decimal: ${getNthDecimalDigit(number, 4)}`);
console.log(`5th digit after decimal: ${getNthDecimalDigit(number, 5)}`);
console.log(`6th digit after decimal: ${getNthDecimalDigit(number, 6)}`);
// Additional examples
console.log(getNthDecimalDigit(98.7654, 2));
console.log(getNthDecimalDigit(-12.345, 3));
console.log(getNthDecimalDigit(1.2, 5));
/*
run:
Number: 123.456789
1st digit after decimal: 4
2nd digit after decimal: 5
3rd digit after decimal: 6
4th digit after decimal: 7
5th digit after decimal: 8
6th digit after decimal: 9
6
5
0
*/