具有 2 位小数的格式(NSDecimalNumber)



我的NSDecimalNumber 中有一个扩展名

extension NSDecimalNumber {
    func format(f: String) -> String {
        return String(format: "%(f)f", self)
    }
}

这应该允许我执行以下操作:

var price = 34.2499999
price.format(f: ".2") // 35.25

相反,我在UICollectionViewCell中得到 0.00 :

func configureCell(_ item: Item) {
        self. item = item
        nameLabel.adjustsFontSizeToFitWidth = true
        priceLabel.adjustsFontSizeToFitWidth = true
        nameLabel.text = self. item.name.capitalized
        priceLabel.text = "£(self. item.price!.format(f: ".2"))"
    }

我想用显示两位小数而不是随机数的实际价格来格式化它。所有价格均从数据库中检索,并且只有 2 位小数。

出于某种原因,当我从扩展中删除格式时,我得到了更多的小数,而数据库中只有 2 个。为什么会发生这种情况,如何解决?

这可能是由于引擎盖下的类型转换。您始终可以使用NSNumberFormatter格式化价格,以为您提供正确的货币格式,而不是像这样使用字符串格式

extension NSNumber {
    func toCurrency() -> String? {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .currency
        return numberFormatter.string(from: self)
    }
}

另请记住在调用此扩展方法之前使用 price 变量初始化NSDecimalNumber

最新更新