将负数 Double 格式化为 Swift 中的货币
Formatting a negative Double into currency in Swift
我想将 -24.5
之类的双精度值格式化为 -.50
之类的货币格式字符串。在 Swift 中我该怎么做?
我遵循了 ,但最终格式为 $-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) // => [=10=].01
print(0.12.formattedAsLocalCurrency) // => [=10=].12
print(1.23.formattedAsLocalCurrency) // => .23
print(12.34.formattedAsLocalCurrency) // => .34
print(123.45.formattedAsLocalCurrency) // => 3.45
print(1234.56.formattedAsLocalCurrency) // => ,234.56
print((-1234.56).formattedAsLocalCurrency) // => -,234.56
我想将 -24.5
之类的双精度值格式化为 -.50
之类的货币格式字符串。在 Swift 中我该怎么做?
我遵循了 $-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) // => [=10=].01
print(0.12.formattedAsLocalCurrency) // => [=10=].12
print(1.23.formattedAsLocalCurrency) // => .23
print(12.34.formattedAsLocalCurrency) // => .34
print(123.45.formattedAsLocalCurrency) // => 3.45
print(1234.56.formattedAsLocalCurrency) // => ,234.56
print((-1234.56).formattedAsLocalCurrency) // => -,234.56