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

1 Answer

0 votes
fun replaceFloatDigit(number: Double, position: Int, newDigit: Char): Double {
    // Validate that newDigit is indeed a single digit
    require(newDigit.isDigit()) { "Replacement must be a digit (0-9)." }

    // Convert number to string with fixed precision (10 decimal places)
    val strNum = String.format("%.10f", number)

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

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

    // Replace digit (strings are immutable, so build a new one)
    val modified = StringBuilder(strNum).apply {
        setCharAt(position, newDigit)
    }.toString()

    // Convert back to Double
    return modified.toDouble()
}

fun main() {
    try {
        val num = 89710.291
        val pos = 2        // 0-based index
        val newDigit = '8'

        val result = replaceFloatDigit(num, pos, newDigit)
        // Print result with 3 decimal places
        println("Modified number: %.3f".format(result))
    } catch (e: Exception) {
        println("Error: ${e.message}")
    }
}



/*
run:

Modified number: 89810.291

*/

 



answered Nov 17, 2025 by avibootz
...