我使用NSLengthFormatter显示正确的实体,如米,脚,码等. 该方法有效,但我没有得到正确数量的小数位数. let distance = getDistanceAsDouble() //636.62084358567 in meters let format = String(format: "%.1f",distance)
该方法有效,但我没有得到正确数量的小数位数.
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(格式:“”…再次.这不起作用,因为formattedDistance包含“yd”(或其他实体).
我该如何解决这个问题?
NSLengthFormatter有一个属性numberFormatter:NSNumberFormatter,所以用它来设置它,就像这样……if let formattedDouble = Double(format) { let lengthFormatter = NSLengthFormatter() lengthFormatter.numberFormatter.maximumFractionDigits = 1 // ***** let formattedDistance = lengthFormatter.stringFromMeters(formattedDouble) print("\(formattedDistance)") }