Reputation: 3046
I am trying to format a number from 1000 to $1,000.00 or 12.99 to $12.99 or 100 to $100.00 (etc)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
let formattedNumberTotalCost = numberFormatter.string(from: NSNumber(value:self.itemCost))
//return 1,000
let totalCostStringLeft = String(format: "$%.02f", formattedNumberTotalCost!)
//returns 0.00 SHOULD return $1,000.00
leftui.text = totalCostStringLeft
//shows 0.00
What am I doing wrong here?
Upvotes: 0
Views: 866
Reputation: 1610
Just to provide a complete answer here, the NumberFormatter
will do all you require - you just need to tell it to format the string as a currency.
Change:
numberFormatter.numberStyle = .decimal
to:
numberFormatter.numberStyle = .currency
and the work is done. Drop the assignment to totalCostStringLeft
and assign
leftui.text = formattedNumberTotalCost
Your answer wasn't working as it tried to combine two methods of formatting numbers as strings. The particular error was using a "%f" formatting string and then passing a string where it expected a floating-point value.
Upvotes: 1