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

1 Answer

0 votes
fun replaceAllDigits(num: Double, oldDigit: Char, newDigit: Char): Double {
    // Format the number to a string with 3 decimal places
    val strNum = String.format("%.3f", num)

    // Replace all occurrences of oldDigit with newDigit
    val modifiedStr = strNum.map { if (it == oldDigit) newDigit else it }.joinToString("")

    // Convert the modified string back to Double
    return modifiedStr.toDoubleOrNull() ?: 0.0
}

fun main() {
    println("%.3f".format(replaceAllDigits(82420.291, '2', '6')))
    println("%.3f".format(replaceAllDigits(111.11, '1', '5')))
}



/*
run:

86460.691
555.550

*/

 



answered 11 hours ago by avibootz

Related questions

...