backslash-f
backslash-f

Reputation: 8183

Swift 3 and NumberFormatter (.currency) == ¤?

Xcode 8.0 (8A218a) GM
Target: iOS 10 (Swift 3)

Consider the following code:

let number = NSDecimalNumber(decimal: 22.4)

let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency
numberFormatter.locale = Locale.current

let result = numberFormatter.string(from: number)
print(result!)

The result is:

¤22.40

(I have no idea what ¤ means.)

But if I initialize the locale such as:

numberFormatter.locale = Locale(identifier: "en_US")

The result will be:

$22.40

... which is what I'd expect in the first place.

Notice that this works in a Playground tho:

enter image description here

The problem seems to happen only on devices/simulators via Xcode launching.
(I tested on two different macOS -- at my workplace and at home.)

Any ideas on what's going on?

Upvotes: 11

Views: 20718

Answers (4)

apexa chovatiya
apexa chovatiya

Reputation: 1

I think your device language set to be chinese that is why ¤ symbol shown as currency symbol

Upvotes: 0

D. Pratt
D. Pratt

Reputation: 464

This was happening to me in the Simulator, turns out it was an error in my scheme setup. Checkout the following steps:

  1. Click on Set Active Scheme (click directly to the left of the simulator type i.e. iPhone 7 Plus etc.)
  2. Click Edit Scheme...
  3. Click into the Run settings on the left
  4. Set Application Region to desired region
  5. Set Application Language to desired language
  6. Try running your application again, you should no longer have it displaying the "¤" symbol and instead it should reflect the correct currency symbol.

Upvotes: 5

Nam Pham
Nam Pham

Reputation: 944

I have same problems and I solve it by below code. Hope it is useful

func formatCurrency(value: Double) -> String {
    let formatter = NumberFormatter()
    formatter.numberStyle = .currency
    formatter.maximumFractionDigits = 2
    formatter.locale = Locale(identifier: Locale.current.identifier)
    let result = formatter.string(from: value as NSNumber)
    return result!
}

Upvotes: 15

backslash-f
backslash-f

Reputation: 8183

Answering my own question: recreate the project. :\

The project was started off in Xcode 7 + Swift 2 and then "migrated" to Xcode 8 + Swift 3 (manually). Something must have gone wrong. I don't know what (and I don't want to know).

This wasn't a huge project, so I spent like 40 minutes moving files around. If that was a big project I would be f....d by now.

Xcode pls.

Upvotes: 1

Related Questions