在swift中键入double to String的类型

时间:2015-01-24 22:28:53

标签: swift

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类型的价格之间留出额外的间距。能帮帮我吧。

2 个答案:

答案 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"