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

1 Answer

0 votes
import java.text.DecimalFormat;

public class ReplaceFloatDigitProgram {

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

        // Convert number to string with fixed precision
        DecimalFormat df = new DecimalFormat("0.0000000000"); // 10 decimal places
        String strNum = df.format(number);

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

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

        // Replace digit
        StringBuilder sb = new StringBuilder(strNum);
        sb.setCharAt(position, newDigit);

        // Convert back to double
        return Double.parseDouble(sb.toString());
    }

    public static void main(String[] args) {
        try {
            double num = 89710.291;
            int pos = 2; // 0-based index
            char newDigit = '8';

            double result = replaceFloatDigit(num, pos, newDigit);
            System.out.printf("Modified number: %.3f%n", result);

        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}



/*
run:

Modified number: 89810.291

*/

 



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