Reputation:
I want to format a Double value such as -24.5
into a currency formatted string like -$24.50
. How would I do that in Swift?
I followed this post, but it ends up formatting as $-24.50
(negative sign after the $), which is not what I want.
Is there a more elegant solution to achieve this, besides something like this?
if value < 0 {
return String(format: "-$%.02f", -value)
} else {
return String(format: "$%.02f", value)
}
Upvotes: 0
Views: 2830
Reputation: 63274
Use 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
Upvotes: 4