func getListing(var qty: Int) -> String{
if(qty < qtyInStock) {
return title + ", by " + author + " ($" + NSString(format:"%\(price).2d", price) + ")...In Stock"
}
else {
//return NSString(format: "%\(price)d") + author
return title + ", by " + author + " ($" + NSString(format:"%\(price).2d") + ")...Sold out"
}
}
输出:The Great Gatsby,作者:F。Scott Fitzgerald($ 00)......有货&#34;
我无法在输出中获得价格值。另外,我不会在$ sign和double类型的价格之间留出额外的间距。能帮帮我吧。
答案 0 :(得分:1)
使用%.2f
代替%\(price).2d
答案 1 :(得分:1)
您应该使用NSNumberFormatter格式化数字。只需创建一个只读的计算属性Double扩展如下:
extension Double {
var currency: String {
let styler = NSNumberFormatter()
styler.minimumFractionDigits = 2
styler.maximumFractionDigits = 2
styler.numberStyle = .CurrencyStyle
styler.currencySymbol = "$"
return styler.stringFromNumber(self)!
}
}
199.99.currency // "$199.99"