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

1 Answer

0 votes
import Foundation

func replaceAllDigits(_ num: Double, oldDigit: Character, newDigit: Character) -> Double {
    // Format the number to a string with 3 decimal places
    let strNum = String(format: "%.3f", num)

    // Replace all occurrences of oldDigit with newDigit
    let modifiedStr = strNum.map { $0 == oldDigit ? newDigit : $0 }

    // Convert the modified string back to Double
    return Double(String(modifiedStr)) ?? 0.0
}

print(String(format: "%.3f", replaceAllDigits(82420.291, oldDigit: "2", newDigit: "6")))
print(String(format: "%.3f", replaceAllDigits(111.11, oldDigit: "1", newDigit: "5")))



/*
run:

86460.691
555.550

*/

 



answered 14 hours ago by avibootz

Related questions

...