Convert String to CGFloat in Swift

后端 未结 12 1157
长情又很酷
长情又很酷 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
    
    0 讨论(0)
  • 2021-02-03 17:18

    Good question. There is not in fact any pure Swift API for converting a string that represents a CGFloat into a CGFloat. The only string-represented number that pure Swift lets you convert to a number is an integer. You'll have to use some other approach from some other library - for example, start with Foundation's NSString or C's (Darwin's) strtod.

    0 讨论(0)
  • 2021-02-03 17:21

    If you want a safe way to do this, here is a possibility:

    let str = "32.4"
    if let n = NSNumberFormatter().numberFromString(str) {
        let f = CGFloat(n)
    }
    

    If you change str to "bob", it won't get converted to a float, while most of the other answers will get turned into 0.0.

    For Swift 3.0, I'd do something like this:

    let str = "32.4"
    guard let n = NSNumberFormatter().number(from: str) else { return }
    // Use `n` here
    

    In Swift 4, NSNumberFormatter has been renamed to NumberFormatter:

    let str = "32.4"
    guard let n = NumberFormatter().number(from: str) else { return }
    
    0 讨论(0)
  • 2021-02-03 17:21

    in Swift 3.0

    if let n = NumberFormatter().number(from: string) {
      let f = CGFloat(n)
    }
    

    or this if you are sure that string meets all requirements

    let n = CGFloat(NumberFormatter().number(from: string)!)
    
    0 讨论(0)
  • 2021-02-03 17:23

    You should cast string to double and then cast from double to CGFloat, Let try this:

    let fl: CGFloat = CGFloat((str as NSString).doubleValue)
    
    0 讨论(0)
  • 2021-02-03 17:23

    Simple one line solution:

    let pi = CGFloat(Double("3.14") ?? 0)
    
    0 讨论(0)
提交回复
热议问题