How to replace all occurrences of a specific digit in a floating-point number with Java

1 Answer

0 votes
public class ReplaceDigitsInFloat {

    public static double replaceAllDigits(double num, char oldDigit, char newDigit) {
        // Format the number to a string with 3 decimal places
        String strNum = String.format("%.3f", num);

        // Replace all occurrences of oldDigit with newDigit
        strNum = strNum.replace(oldDigit, newDigit);

        // Convert the modified string back to a double
        return Double.parseDouble(strNum);
    }

    public static void main(String[] args) {
        System.out.printf("%.3f%n", replaceAllDigits(82420.291, '2', '6'));
        System.out.printf("%.3f%n", replaceAllDigits(111.11, '1', '5'));
    }
}



/*
run:

86460.691
555.550

*/

 



answered 18 hours ago by avibootz

Related questions

...