Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 214
backslash-f Avatar asked Sep 12 '16 20:09

backslash-f


3 Answers

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!
}
like image 193
Nam Pham Avatar answered Nov 12 '22 07:11

Nam Pham


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.
like image 26
D. Pratt Avatar answered Nov 12 '22 06:11

D. Pratt


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.

like image 1
backslash-f Avatar answered Nov 12 '22 07:11

backslash-f