How to get the Nth digit after the decimal point of a float number in TypeScript

2 Answers

0 votes
const f = 895.98731;
   
const N = 4;

console.log(f.toString().split('.')[1][N - 1]); 
 
 
    
/*
run:
     
"3" 
        
*/

 



answered Jun 17, 2022 by avibootz
0 votes
/**
 * Returns the Nth digit after the decimal point of a number.
 *
 * Examples:
 * getNthDecimalDigit(123.456789, 1) -> 4
 * getNthDecimalDigit(123.456789, 2) -> 5
 * getNthDecimalDigit(123.456789, 3) -> 6
 *
 * @param value - The number to inspect.
 * @param position - The digit position after the decimal point (1-based).
 * @returns The Nth digit after the decimal point.
 * @throws TypeError if position is not a positive integer.
 */
function getNthDecimalDigit(value: number, position: number): number {
    // Validate position
    if (!Number.isInteger(position) || position < 1) {
        throw new TypeError(
            "position must be a positive integer."
        );
    }

    // Convert number to a positive string and extract the decimal part
    const decimalPart: string = String(Math.abs(value)).split(".")[1] ?? "";

    // Return the requested digit or 0 if it does not exist
    return Number(decimalPart[position - 1] ?? "0");
}

// -----------------------------------------------------------------------------
// Usage Examples
// -----------------------------------------------------------------------------

const number: 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
const example1: number = 98.7654;
const example2: number = -12.345;
const example3: number = 1.2;

console.log(getNthDecimalDigit(example1, 2)); 
console.log(getNthDecimalDigit(example2, 3)); 
console.log(getNthDecimalDigit(example3, 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

*/

 



answered 13 hours ago by avibootz

Related questions

...