Convert String to CGFloat in Swift

后端 未结 12 1165
长情又很酷
长情又很酷 2021-02-03 17:05

I\'m new to Swift, how can I convert a String to CGFloat?

I tried:

var fl: CGFloat = str as CGFloat
var fl: CGFloat = (CGFloat)str
var fl: CGFloat = CGFl         


        
12条回答
  •  被撕碎了的回忆
    2021-02-03 17:18

    While the other answers are correct, but the result you see will have trailing decimals.

    For example:

    let str = "3.141592654"
    let foo = CGFloat((str as NSString).floatValue)
    

    Result:

    3.14159274101257
    

    To get a proper value back from the string, try the following:

    let str : String = "3.141592654"
    let secStr : NSString = str as NSString
    let flt : CGFloat = CGFloat(secStr.doubleValue)
    

    Result:

    3.141592654
    

提交回复
热议问题