ios - 格式化为 2 位小数 (NSDecimalNumber)

标签 ios swift uicollectionview swift3 number-formatting

我的 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 个小数。为什么会发生这种情况,如何解决?

最佳答案

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

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

另外记得在调用这个扩展方法之前用你的价格变量初始化一个NSDecimalNumber

关于ios - 格式化为 2 位小数 (NSDecimalNumber),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41513735/

相关文章:

ios - 创建类似 Instagram 的照片提要

ios - 类型 'MapViewController' 没有成员 'mapTypeChanged' Swift Big Nerd Ranch Guide

swift - 生成.pb.swift模型时包含单词 "Id"的Protobuf字段名称将其大写为 "ID"

IOS Swift 获取选定的图像路径

ios - 使用 swift 在 Sqlite 中存储和检索图像

ios - 在 swift3 中通过 Alamofire 发出请求时出现 404 错误

arrays - 如何在 swift 中搜索 JSON 文件?

ios - tapGestureRecognizer.location 在 UICollectionView 中带来 nil

ios - UICollectionView 重新加载数据问题

ios - `UICollectionView`什么时候结束