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
    }

 

 
posted on 2025-01-14 10:50  懂事长qingzZ  阅读(23)  评论(0编辑  收藏  举报