How to extract a float from a string in Swift

1 Answer

0 votes
import Foundation

let text = "The price is 148.95 dollars"
let pattern = "[-+]?\\d*\\.\\d+|\\d+"

if let regex = try? NSRegularExpression(pattern: pattern),
   let match = regex.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) {

    let matchedString = (text as NSString).substring(with: match.range)
    if let number = Double(matchedString) {
        print(String(format: "Extracted float: %.2f", number))
    } else {
        print("Error parsing float.")
    }
} else {
    print("No float found.")
}




/*
run:

Extracted float: 148.95

*/

 



answered Jul 29, 2025 by avibootz
...