object ReplaceFloatDigitDemo {
/**
* Replace a digit at a given position in a floating-point number.
*/
def replaceFloatDigit(number: Double, position: Int, newDigit: Char): Double = {
// Validate that newDigit is indeed a single digit
if (!newDigit.isDigit) {
throw new IllegalArgumentException("Replacement must be a digit (0-9).")
}
// Convert number to string with fixed precision (10 decimal places)
val strNum = f"$number%.10f"
// 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(position) == '.' || strNum(position) == '-') {
throw new IllegalArgumentException("Position points to a non-digit character.")
}
// Replace digit (strings are immutable, so build a new one)
val modified = strNum.updated(position, newDigit)
// Convert back to Double
modified.toDouble
}
def main(args: Array[String]): Unit = {
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(f"Modified number: $result%.3f")
} catch {
case e: Exception =>
Console.err.println(s"Error: ${e.getMessage}")
}
}
}
/*
run:
Modified number: 89810.291
*/