Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,623 questions

55,358 answers

573 users

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 Nov 18, 2025 by avibootz

Related questions

...