ios - 从货币中删除小数位?

标签 ios swift nsdate

我有以下示例:

// Currencies

var price: Double = 3.20
println("price: \(price)")

let numberFormater = NSNumberFormatter()
numberFormater.locale = locale
numberFormater.numberStyle = NSNumberFormatterStyle.CurrencyStyle
numberFormater.maximumFractionDigits = 2

我想要有 2 个摘要的货币输出。如果货币摘要全部为零,我希望它们不会显示。所以 3,00 应该显示为:3。所有其他值应与两个摘要一起显示。

我该怎么做?

最佳答案

您必须将 numberStyle 设置为 .decimal 样式才能根据 float 是否为偶数设置 minimumFractionDigits 属性:

extension FloatingPoint {
    var isWholeNumber: Bool { isZero ? true : !isNormal ? false : self == rounded() }
}

您还可以扩展 Formatter 并创建静态格式化程序,以避免在运行代码时多次创建格式化程序:

extension Formatter {
    static let currency: NumberFormatter = {
        let numberFormater = NumberFormatter()
        numberFormater.numberStyle = .currency
        return numberFormater
    }()
    static let currencyNoSymbol: NumberFormatter = {
        let numberFormater = NumberFormatter()
        numberFormater.numberStyle = .currency
        numberFormater.currencySymbol = ""
        return numberFormater
    }()
}

extension FloatingPoint {
    var currencyFormatted: String {
        Formatter.currency.minimumFractionDigits = isWholeNumber ? 0 : 2
        return Formatter.currency.string(for: self) ?? ""
    }
    var currencyNoSymbolFormatted: String {
        Formatter.currencyNoSymbol.minimumFractionDigits = isWholeNumber ? 0 : 2
        return Formatter.currencyNoSymbol.string(for: self) ?? ""
    }
}

Playground 测试:

3.0.currencyFormatted            // "$3"
3.12.currencyFormatted           // "$3.12"
3.2.currencyFormatted            // "$3.20"

3.0.currencyNoSymbolFormatted    // "3"
3.12.currencyNoSymbolFormatted   // "3.12"
3.2.currencyNoSymbolFormatted    // "3.20"

let price = 3.2
print("price: \(price.currencyFormatted)")  // "price: $3.20\n"

关于ios - 从货币中删除小数位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30947017/

相关文章:

ios - 泄漏工具未发现泄漏,但未释放内存

c# - 无法让 TouchPhase 在 Unity3D 中工作

ios - 在 iOS 中解析和接收电子邮件

ios - 带有自定义单元格的 ViewController 内的 UITableView 没有 Storyboard

ios - 在使用自定义 UITableViewCell 时解决没有自定义 init 方法的问题

swift - 如何在 Swift 中创建一个不可变的结构实例数组作为实例变量?

ios - 通过在本地更新数组模型来重新加载特定的表格 View 单元

objective-c - 如何将 .hour() 和 .min() 从 Swift 转换为 Objective-C?

ios - 如何从单个文本文件中提取不同语言的日期?

ios - 如何在iOS中按创建日期对文档目录中的文件进行排序?