1.NSString 的 doubleValue 方法
let str = "123.45" let floatValue = CGFloat((str as NSString).doubleValue) print(floatValue) // 输出 123.45
2.使用 NumberFormatter 进行转换
private func strConvertFloat(str: String) -> CGFloat { let formatter = NumberFormatter() formatter.numberStyle = .decimal if let number = formatter.number(from: str) { let floatValue = CGFloat(truncating: number) print(floatValue) // 输出 123.45 return floatValue } print("无法转换为 CGFloat") return 0 }