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

1 Answer

0 votes
import Foundation

// Define possible errors for validation
enum ReplaceDigitError: Error {
    case invalidDigit
    case positionOutOfRange
    case nonDigitCharacter
}

// Function to replace a digit at a given position in a floating-point number
func replaceFloatDigit(number: Double, position: Int, newDigit: Character) throws -> Double {
    // Validate that newDigit is indeed a single digit
    guard newDigit.isNumber else {
        throw ReplaceDigitError.invalidDigit
    }
    
    // Convert number to string with fixed precision (10 decimal places)
    let strNum = String(format: "%.10f", number)
    
    // Validate position
    guard position >= 0 && position < strNum.count else {
        throw ReplaceDigitError.positionOutOfRange
    }
    
    // Ensure position points to a digit
    let index = strNum.index(strNum.startIndex, offsetBy: position)
    let ch = strNum[index]
    if ch == "." || ch == "-" {
        throw ReplaceDigitError.nonDigitCharacter
    }
    
    // Replace digit (strings are immutable, so build a new one)
    var chars = Array(strNum)
    chars[position] = newDigit
    let modified = String(chars)
    
    // Convert back to Double
    guard let result = Double(modified) else {
        throw ReplaceDigitError.invalidDigit
    }
    
    return result
}

// Main function
func main() {
    do {
        let num = 89710.291
        let pos = 2        // 0-based index
        let newDigit: Character = "8"
        
        let result = try replaceFloatDigit(number: num, position: pos, newDigit: newDigit)
        // Print result with 3 decimal places
        print(String(format: "Modified number: %.3f", result))
    } catch {
        print("Error: \(error)")
    }
}

main()



/*
run:
  
Modified number: 89810.291
  
*/

 



answered Nov 17, 2025 by avibootz
...