How to get the Nth digit of a number from the left with BigInt support in JavaScript

1 Answer

0 votes
/**
 * Returns the N-th digit of a BigInt counting from the left.
 *
 * Examples:
 * getDigitFromLeftBigInt(12345n, 1) === 1
 * getDigitFromLeftBigInt(12345n, 3) === 3
 * getDigitFromLeftBigInt(12345n, 5) === 5
 *
 * @param {bigint} number - The input BigInt.
 * @param {number} position - The digit position (1-based, from the left).
 * @returns {number} The digit at the specified position.
 * @throws {TypeError} If number is not a BigInt.
 * @throws {RangeError} If position is invalid.
 */
function getDigitFromLeftBigInt(number, position) {
    if (typeof number !== "bigint") {
        throw new TypeError("Number must be a BigInt.");
    }

    if (!Number.isInteger(position) || position < 1) {
        throw new RangeError("Position must be a positive integer.");
    }

    // Convert the absolute value to a string.
    const digits = (number < 0n ? -number : number).toString();

    if (position > digits.length) {
        throw new RangeError("Position is out of range.");
    }

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

// Example usage
console.log(getDigitFromLeftBigInt(18092n, 3)); 
console.log(getDigitFromLeftBigInt(180927345162343n, 4)); 
console.log(getDigitFromLeftBigInt(180927365162341n, 8)); 
console.log(getDigitFromLeftBigInt(123180927345162341n, 12)); 


/*
run:

0
9
6
5

*/

 



answered Oct 13 by avibootz

Related questions

...