package main
import (
"errors"
"fmt"
"strconv"
)
// replaceFloatDigit replaces a digit at a given position in a floating-point number.
// number: the float64 input
// position: 0-based index in the string representation
// newDigit: the replacement character (must be '0'–'9')
func replaceFloatDigit(number float64, position int, newDigit rune) (float64, error) {
// Validate that newDigit is indeed a single digit
if newDigit < '0' || newDigit > '9' {
return 0, errors.New("replacement must be a digit (0-9)")
}
// Convert number to string with fixed precision (10 decimal places)
strNum := fmt.Sprintf("%.10f", number)
// Validate position
if position < 0 || position >= len(strNum) {
return 0, errors.New("position is out of range for the number string")
}
// Ensure position points to a digit
if strNum[position] == '.' || strNum[position] == '-' {
return 0, errors.New("position points to a non-digit character")
}
// Replace digit
// Strings in Go are immutable, so we convert to a slice of runes
runes := []rune(strNum)
runes[position] = newDigit
modified := string(runes)
// Convert back to float
result, err := strconv.ParseFloat(modified, 64)
if err != nil {
return 0, errors.New("conversion failed")
}
return result, nil
}
func main() {
num := 89710.291
pos := 2 // 0-based index
newDigit := '8' // rune literal for digit '8'
// Call the function and handle errors
result, err := replaceFloatDigit(num, pos, newDigit)
if err != nil {
fmt.Println("Error:", err)
return
}
// Print result with 3 decimal places
fmt.Printf("Modified number: %.3f\n", result)
}
/*
run:
Modified number: 89810.291
*/