在Swift中将负Double格式化为货币

时间:2017-12-31 02:19:03

标签: swift string swift3

我想将-24.5之类的Double值格式化为货币格式的字符串-$24.50。我怎么能在Swift中做到这一点?

我关注了this post,但最终格式化为$-24.50($后面的负号),这不是我想要的。

除此之外还有更优雅的解决方案吗?

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

1 个答案:

答案 0 :(得分:3)

使用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