Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to replace a digit in a floating-point number by index with TypeScript

1 Answer

0 votes
function replaceFloatDigit(
    number: number,
    position: number,
    newDigit: string
): number {
    // Validate that newDigit is indeed a single digit
    if (newDigit.length !== 1 || newDigit < '0' || newDigit > '9') {
        throw new Error("Replacement must be a digit (0-9).");
    }

    // Convert number to string with fixed precision (10 decimal places)
    let strNum: string = number.toFixed(10);

    // Validate position
    if (position < 0 || position >= strNum.length) {
        throw new Error("Position is out of range for the number string.");
    }

    // Ensure position points to a digit
    const charAtPos: string = strNum[position];
    if (charAtPos === '.' || charAtPos === '-') {
        throw new Error("Position points to a non-digit character.");
    }

    // Replace digit
    strNum = strNum.substring(0, position) + newDigit + strNum.substring(position + 1);

    // Convert back to float
    return parseFloat(strNum);
}

// Example usage
try {
    const num: number = 89710.291;
    const pos: number = 2;          // 0-based index
    const newDigit: string = '8';

    const result: number = replaceFloatDigit(num, pos, newDigit);
    console.log(`Modified number: ${result.toFixed(3)}`);
} catch (e) {
    if (e instanceof Error) {
        console.error("Error: " + e.message);
    }
}



/*
run:

Modified number: 89810.291

*/

 



answered Nov 17, 2025 by avibootz
...