formattedAsLocalCurrency

formattedAsLocalCurrency

我想将双精度值(如-24.5)格式化为货币格式的字符串(如-$24.50)。我怎么能这么快?
我遵循了this post,但它最终格式化为$-24.50($后面的负号),这不是我想要的。
除此之外,还有更优雅的解决方案吗?

if value < 0 {
    return String(format: "-$%.02f", -value)
} else {
    return String(format: "$%.02f", value)
}

最佳答案

使用NumberFormatter

import Foundation

extension Double {
    var formattedAsLocalCurrency: String {
        let currencyFormatter = NumberFormatter()
        currencyFormatter.usesGroupingSeparator = true
        currencyFormatter.numberStyle = .currency
        currencyFormatter.locale = Locale.current
        return currencyFormatter.string(from: NSNumber(value: self))!
    }
}

print(0.01.formattedAsLocalCurrency) // => $0.01
print(0.12.formattedAsLocalCurrency) // => $0.12
print(1.23.formattedAsLocalCurrency) // => $1.23
print(12.34.formattedAsLocalCurrency) // => $12.34
print(123.45.formattedAsLocalCurrency) // => $123.45
print(1234.56.formattedAsLocalCurrency) // => $1,234.56
print((-1234.56).formattedAsLocalCurrency) // => -$1,234.56

10-07 16:37