【问题标题】:Converting CGFloat to String in Swift在 Swift 中将 CGFloat 转换为字符串
【发布时间】:2014-08-06 06:58:02
【问题描述】:

这是我目前在 Swift 中将 CGFloat 转换为 String 的方法:

let x:Float = Float(CGFloat)
let y:Int = Int(x)
let z:String = String(y)

有没有更有效的方法来做到这一点?

【问题讨论】:

    标签: string swift cgfloat


    【解决方案1】:

    你可以使用string interpolation:

    let x: CGFloat = 0.1
    let string = "\(x)" // "0.1"
    

    或者从技术上讲,您可以直接使用 CGFloat 的可打印特性:

    let string = x.description
    

    description 属性来自它实现了Printable 协议,这使得字符串插值成为可能。

    【讨论】:

      【解决方案2】:

      快捷方式:

      let x = CGFloat(12.345)
      let s = String(format: "%.3f", Double(x))
      

      更好的方法,因为它关注语言环境:

      let x = CGFloat(12.345)
      
      let numberFormatter = NSNumberFormatter()
      numberFormatter.numberStyle = .DecimalStyle
      numberFormatter.minimumFractionDigits = 3
      numberFormatter.maximumFractionDigits = 3
      
      let s = numberFormatter.stringFromNumber(x)
      

      【讨论】:

        猜你喜欢
        • 2014-07-31
        • 1970-01-01
        • 1970-01-01
        • 2016-10-22
        • 1970-01-01
        • 2018-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多