0

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?

letsCode
  • 2,774
  • 1
  • 13
  • 37
  • Show how you're creating `numberFormatter`. The first line probably does all you need, assign that to `leftui.text`. The second line is expecting a floating point number, but you're providing a string. – Chris Shaw Oct 04 '19 at 02:22
  • add @ChrisShaw its not adding the .00 to the end of this specific number... (1200). it changes 1200 to 1,200, but not 1,200.00 ... or if it 15.50, its removing the 0.... so the result is 15.5 – letsCode Oct 04 '19 at 02:24
  • You are mixing up two ways of formatting the number. Pick one or the other [from this answer](https://stackoverflow.com/a/41558921/335858) - either use `numberFormatter` with currency style all the way (solution #2 from the answer) or use `String(format:...)` solution with `itemCost` converted to `float`. You get `0.00` because you pass a string instead of `float`. – Sergey Kalinichenko Oct 04 '19 at 02:29
  • 1
    Change `numberFormatter.numberStyle = .decimal` to `... = .currency`, then ditch the `let totalCostStringLeft = ...` line and assign `leftui.text = formattedNumberTotalCost` – Chris Shaw Oct 04 '19 at 02:36

1 Answers1

1

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.

Chris Shaw
  • 1,610
  • 2
  • 10
  • 14