我使用NSLengthFormatter显示正确的实体,如米,脚,码等.
该方法有效,但我没有得到正确数量的小数位数.
let distance = getDistanceAsDouble() //636.62084358567 in meters let format = String(format: "%.1f",distance) //636.6 if let formattedDouble = Double(format) { let lengthFormatter = NSLengthFormatter() let formattedDistance = lengthFormatter.stringFromMeters(formattedDouble) lbl.text = "\(formattedDistance)" // printed: 697.936 yd }
我用Google搜索,但我找不到如何配置NSLengthFormatter.NSNumberFormatter具有类似numberStyle
或的属性maximumFractionDigitis
,但NSLengthFormatter没有...或?
我试图施放formattedDistance
到Double,我可以String(format: ""...
再次使用.这不起作用,因为formattedDistance
包含"yd"(或其他实体).
我该如何解决这个问题?
NSLengthFormatter
有一个属性numberFormatter: NSNumberFormatter
,所以用它来设置它,就像这样......
if let formattedDouble = Double(format) { let lengthFormatter = NSLengthFormatter() lengthFormatter.numberFormatter.maximumFractionDigits = 1 // ***** let formattedDistance = lengthFormatter.stringFromMeters(formattedDouble) print("\(formattedDistance)") }