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

1 Answer

0 votes
using System;
using System.Globalization; // CultureInfo
using System.Text;

class ReplaceFloatDigitProgram
{
    // Function to replace a digit at a given position in a floating-point number
    static double ReplaceFloatDigit(double number, int position, char newDigit) {
        // Validate that newDigit is indeed a digit
        if (newDigit < '0' || newDigit > '9') {
            throw new ArgumentException("Replacement must be a digit (0-9).");
        }

        // Convert number to string with fixed precision
        string strNum = number.ToString("F10", CultureInfo.InvariantCulture); // 10 decimal places

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

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

        // Replace digit
        var sb = new StringBuilder(strNum);
        sb[position] = newDigit;

        // Convert back to double
        return double.Parse(sb.ToString(), CultureInfo.InvariantCulture);
    }

    static void Main()
    {
        try {
            double num = 89710.291;
            int pos = 2; // 0-based index
            char newDigit = '8';

            double result = ReplaceFloatDigit(num, pos, newDigit);
            Console.WriteLine("Modified number: {0:F3}", result);
        }
        catch (Exception e) {
            Console.Error.WriteLine("Error: " + e.Message);
        }
    }
}



/*
run:

Modified number: 89810.291

*/

 



answered Nov 17, 2025 by avibootz
edited Nov 17, 2025 by avibootz
...