我想将像-24.5
这样的Double值格式化为像-$24.50
这样的货币格式化字符串。我怎么会在Swift中这样做?
我跟着this post,但最终格式化为$-24.50
($后的负号),这不是我想要的。
有没有更优雅的解决方案来实现这一目标,除此之外?
if value < 0 {
return String(format: "-$%.02f", -value)
} else {
return String(format: "$%.02f", value)
}
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