"use strict";
/**
* Returns the Nth digit after the decimal point.
*
* Examples:
* getNthDecimalDigit(123.456789, 1) => 4
* getNthDecimalDigit(123.456789, 2) => 5
* getNthDecimalDigit(123.456789, 3) => 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 after the decimal point.
* @throws {TypeError} If the inputs are invalid.
*/
function getNthDecimalDigit(value, position) {
// Validate the number
if (!Number.isFinite(value)) {
throw new TypeError("value must be a finite number.");
}
// Validate the requested position
if (!Number.isInteger(position) || position < 1) {
throw new TypeError("position must be a positive integer.");
}
// Convert to a positive string and extract the decimal part
const decimalPart = String(Math.abs(value)).split(".")[1] || "";
// Return the requested digit or 0 if it doesn't exist
return Number(decimalPart[position - 1] || 0);
}
/**
* Returns the ordinal suffix for a number.
*
* Examples:
* 1 -> 1st
* 2 -> 2nd
* 3 -> 3rd
* 4 -> 4th
*
* @param {number} n
* @returns {string}
*/
function getOrdinal(n) {
const suffixes = ["th", "st", "nd", "rd"];
const remainder100 = n % 100;
return (
n +
(suffixes[(remainder100 - 20) % 10] ||
suffixes[remainder100] ||
suffixes[0])
);
}
// -----------------------------------------------------------------------------
// Usage Examples
// -----------------------------------------------------------------------------
const number = 123.456789;
console.log(`Number: ${number}\n`);
for (let position = 1; position <= 6; position++) {
console.log(
`${getOrdinal(position)} digit after decimal: ${getNthDecimalDigit(
number,
position
)}`
);
}
console.log("\nAdditional Examples:");
console.log(`2nd digit of 98.7654: ${getNthDecimalDigit(98.7654, 2)}`);
console.log(`3rd digit of -12.345: ${getNthDecimalDigit(-12.345, 3)}`);
console.log(`5th digit of 1.2: ${getNthDecimalDigit(1.2, 5)}`);
/*
run:
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
Additional Examples:
2nd digit of 98.7654: 6
3rd digit of -12.345: 5
5th digit of 1.2: 0
*/