这是我目前在Swift中将CGFloat转换为字符串的方法:
let x:Float = Float(CGFloat)
let y:Int = Int(x)
let z:String = String(y)
有没有更有效的方法来做到这一点?
发布于 2014-08-06 15:00:39
您可以使用string interpolation
let x: CGFloat = 0.1
let string = "\(x)" // "0.1"
或者从技术上讲,您可以直接使用CGFloat的可打印特性:
let string = x.description
description
属性来自于它实现了Printable
协议,正是这个协议使得字符串插值成为可能。
发布于 2014-08-06 15:03:27
快速方法:
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)
https://stackoverflow.com/questions/25154087
复制相似问题