Converting CGFloat to String in Swift

前端 未结 2 1862
生来不讨喜
生来不讨喜 2021-02-05 01:46

This is my current way of converting a CGFloat to String in Swift:

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

Is

2条回答
  •  渐次进展
    2021-02-05 02:25

    The fast way:

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

    The better way, because it takes care on locales:

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

提交回复
热议问题