Hello,
How do I format a double into s string currency format?
I can convert a double to a string but can't format it into U.S. currency. I am trying to print the monthly payment in currency format.
This is what I did. I can put numbers into NSNumber but I can't the output there. dblMonthlyPayment is my variable.
I tried:
String(dblMonthlyPayment)
1. class CurrencyFormatter: NumberFormatter {
2. required init?(coder aDecoder: NSCoder) {
3. super.init(coder: aDecoder)
4. }
5. override init() {
6. super.init()
7. self.locale = NSLocale.current
8. self.maximumFractionDigits = 2
9. self.minimumFractionDigits = 2
10. self.alwaysShowsDecimalSeparator = true
11. self.numberStyle = .currency
12. }
13. static let SharedInstance = CurrencyFormatter()
14.
15. }
16. // Print the Monthly Payment.
17. lblMonthlyPayment.text = CurrencyFormatter.SharedInstance.string(from: NSNumber)
In Swift, you can often read the method name to figure out how to use it. In Quinn's example:
let result = NumberFormatter.localizedString(from: 9999.99, number: .currency)This reads, "ask the number formatter for a localized string from the number 9999.99 with the currency number format." So, in your scenario, replace the 9999.99 with an NSNumber object. Here's how you create an NSNumber object from a Double variable:
NSNumber(value: variable)This reads, "create an NSNumber object with the value in 'variable'."