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

2019-04-06 18:54发布

问题:

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:

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?

回答1:

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!
}


回答2:

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.



回答3:

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.


回答4:

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