Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding NumberFormatter for currency in Swift

I have an app where I'm trying to format a Double with NumberFormetter but the output I'm getting does not match the output in other apps.

Here is the code I'm using...

let price:Double = 25
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = NSLocale.current

let priceFormatter = currencyFormatter.string(for: price)

myLabel.text = priceFormatter

With the above code and with the phone's Regionset to China in my App I get 25,00 CNY but in two other third-party-apps the output is CN¥25.00.

What am I doing wrong?

Region Set to China:

My App
25,00 CNY

Other Apps
CN¥25.00

Region Set to France:

My App
25,00€

Other Apps
€25,00

But when the region is set to United States I get the same notation in all three (3) apps.

Region Set to United States:

My App
$25.00

Other Apps
$25.00

I'm a little concerned especially with the output when the region is set to China because besides the notation being different I also get a different symbol CNY vs CN¥.

Any suggestions, am I doing something wrong?

like image 530
fs_tigre Avatar asked Sep 12 '25 07:09

fs_tigre


2 Answers

Spoiler the other apps are doing it wrong, your output is correct !

like image 121
Damien Bannerot Avatar answered Sep 13 '25 22:09

Damien Bannerot


You can specify the format you want the output. Exemple :

let number: NSNumber = 25
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale.init(identifier: "cn_CN") // or "en_US", "fr_FR"
numberFormatter.positiveFormat = "#0.00 ¤"
let price = numberFormatter.string(from: number)

which gives the output

25.00 CN¥

You can change the format to get different outputs:

"#0.00 ¤" => 25.00 CN¥

"#0.00 ¤¤" => 25.00 CNY

"#0.00 ¤¤¤" => 25.00 Chinese yuan

like image 35
Omar Chaabouni Avatar answered Sep 13 '25 21:09

Omar Chaabouni