How to display arabic numerics when using NSNumberFormatter with India locale? - ios

The following with return १२३४५६७८९० instead of 123456790:
let numberFormatter = NSNumberFormatter()
numberFormatter.locale = NSLocale(localeIdentifier: "hi_IN")
numberFormatter.stringFromNumber(1234567890)
Is there a way to configure NSNumberFormatter so that arabic numeral is used?

If you want to get ١٢٣٤٥٦٧٨٩٠ then use the localeIdentifier ar_SA or ar_IN
If you want to still get the return value as 123456789 then you can use any other indian locale that does not contain the numerals in its respective script. For e.g. en_IN. Refer https://gist.github.com/jacobbubu/1836273 for the locale identifiers that you want to use.

Related

Swift IAP SKProduct wrong price displayed

I use In App Purchases in an iOS app. I want to display the price in the right format depending on the user/device.
Here's my code:
let price=product.price
let numberFormatter = NumberFormatter()
numberFoxrmatter.formatterBehavior = .behavior10_4 //doesn't change anything if I remove this line
numberFormatter.numberStyle = .currency
numberFormatter.locale = product.priceLocale
let formattedPrice=numberFormatter.string(from: price)
But the currency symbol is not the good one and/or misplaced in some cases.
In my example, the price product is $19.99 or 20,99€.
Examples
From device:
product.priceLocale: en_FR#currency=EUR (fixed)
Locale.current: en_FR (current)
Output: €20,99
Should display: 20,99€
From simulator:
product.priceLocale: en_FR#currency=EUR (fixed)
Locale.current: en_US (current)
Output: $20.99
Should display: 20,99€ or $19.99
I have several users who have the same issue with other currencies where the symbol should be placed after the price, unlike the dollars format. And another user who sees $7290 instead of 7290₸ (which is quite a different price...).
I'm pretty sure it has to do with the language setting or the Locale.current. But if I change my primary language to French on my device, I have the same price "€20,99". What is weird is my Locale.current switches to en_US (current).
Any way to solve this?
Another solution I'd be happy with: display the price in dollars for everyone, whatever the user's language & currency.
Try this
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
// localize to your grouping and decimal separator
currencyFormatter.locale = Locale.current
// We'll force unwrap with the !, if you've got defined data you may need more error checking
let priceString = currencyFormatter.string(from: 9999.99)!
print(priceString) // Displays $9,999.99 in the US locale
Example
currencyFormatter.locale = Locale(identifier: "fr_FR")
if let priceString = currencyFormatter.string(from: 9999.99) {
print(priceString) // Displays 9 999,99 € in the French locale
}
For more detail please check https://supereasyapps.com/blog/2016/2/8/how-to-use-nsnumberformatter-in-swift-to-make-currency-numbers-easy-to-read
Locale setting is key to the correct output. en_FR reads like English language and french region. This will result in formatted output for an english speaker with french price -> €10.00
Use the simulator and set region & language to french and use Locale.current. It should read fr_FR and give correct output. 10,00€
Did you try to change language and region on the simulator and does it effect priceLocale?

How to convert number inputted in any locale inside a UITextField into English number in iOS Swift

I am trying to get some decimal number from the user inside a UITextfield in iOS Swift. Now the user can input number in his or her local number format as per the locale Settings in iOS. I want to convert this number which is in the user's mother tongue into English number. I searched a lot in this site (stackoverflow.com) and the majority of answers are for conversion from one locale (Chinese, or Arabic or Persian) into English but I want to convert number inputted into any locale format into English. How can I do this? So in nutshell, my question is whether the number being inputted in UITextField is in Hindi, Arabic, Persian, Chinese or whatsoever format as per the locale, I want to convert it into English Number format.
you can use NumberFormatter for that.
check below example:
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
let localNumberInStr = "૨૩"
guard let str = numberFormatter.number(from: localNumberInStr) else {return}
print(str) //"23"
When you check the devices locale you know which locale the user is using.
let locale = Locale.current
Just to improve upon Dharmesh answer, here is the answer wrapped in a helper method for use throughout the code. Obviously, it assumes that while getting user input via UITextField one has considered the number set in the user's locale settings.
func convertLocaleNumberIntoEnglish(localeNumberString: String?) -> String? {
guard let ulocaleNumberString = localeNumberString else {return nil}
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
let localNumberInStr = ulocaleNumberString
guard let number = numberFormatter.number(from: localNumberInStr) else {return nil}
let str = String(format:"%f", number.doubleValue)
return str
}

Formatting localized numbers with unit symbols

Situation
I want to format a Double 23.54435678 into a String like 23.54 fps respecting the user's locale.
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
let formatted = formatter.string(from: fps as NSNumber)! + " fps"
For the localized number formatting I use DateFormatter.
Question
How should I handle the unit part? Is it valid to just append the unit to the formatted number? Is the placement of the symbol not locale dependent? How do I handle that?
Cocoa has no built-in support for the unit "frames per second", so you will have to provide the suffix yourself, e.g. using Xcode's localization system.
You still need to format the numeric value with NumberFormatter for the current locale and then insert the resulting number string into the localized format string:
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
let numberString = formatter.string(from: fps)
let formatString = NSLocalizedString("%# fps", comment: "") // provide localizations via .strings files
let fpsString = String(format: formatString, arguments: numberString)
If unit placement is locale-dependent (you will have to this find out yourself for the target locales of your app), you have to deal with this manually as well. You can leverage the localization system here by providing localizations with an adequately positioned placeholder for the numeric value, e.g. %# fps for English and x %# yz for... well, Fantasy Language.

NumberFormatter turn percent value to double get nil

I want to turn String precent value into Double by:
let formatter = NumberFormatter()
formatter.numberStyle = .percent
let a = formatter.number(from: "12.5%")
print(a)
It works well in playground. But when test in project under "romana"(Română) language, it prints nil. If i change 12.5% to int type percentage value like 56% it works no problem.
Any idea?
Attached the language setting page.
If i change 12.5% to int type percentage value like 56% it works no problem.
This usually means that the locale settings use a different character for decimal separator, i.e. comma , instead of dot .
Switching to 12,5% should fix this problem.
I got all the source number with . separator
If your numbers are hard-coded in the source, you should not rely on user-selected locale. Use system locale for dealing with hard-coded inputs:
formatter.locale = Locale.system
[Locale.system is] The generic locale that contains fixed “backstop” settings that provide values for otherwise undefined keys. Use the system locale when you don’t want any localizations.
Try this
let formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter.locale = Locale(identifier: "EN")
let a = formatter.number(from: "12.5%")

Collect iOS currency symbols for bitmap font?

My app is displaying the price of an in app purchase product. How can I (at design time) enumerate all the currency symbols and characters used in all of Apple's international app stores? I am displaying text in my app using "texture atlas" based bitmap fonts, i.e. I have to manually include each character I want to display.
I realize that this is a moving target, so I plan to make my logic forgiving. For example if some future equivalent of the Euro symbol is added by Apple and somebody's running an old version of my app, I will silently drop that character and just display the numeric part as "2.99" or "2,99" etc.
But how can I make my list as accurate as possible today, per Apple's official list?
Here's how the string is formatted (straight from Apple's sample):
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setLocale:product.priceLocale];
NSString *formattedString = [numberFormatter stringFromNumber:product.price];
Nobody's rushing to answer this, so here's the best option I've found so far. Basically, the approach would be scraping the currency symbols and Latin character alternates from the following page:
http://en.wikipedia.org/wiki/Currency_symbol#List_of_presently-circulating_currency_symbols
Notice that there is a generic currency symbol that can be used as a fallback.
If anybody has a better answer (meaning somehow gleaned from Apple), I'll be happy to accept your answer over this one.
I quickly wrote a Swift playground to grab the NumberFormatter's output for every available locale. Filtering this to only include currency symbols and punctuation gives a relatively complete set of characters to include.
let price = 0 as NSDecimalNumber
let availableIdentifiers = Locale.availableIdentifiers
var allCurrencySymbols: String = ""
for identifier in availableIdentifiers
{
let locale = Locale(identifier: identifier)
let formatter = NumberFormatter()
formatter.formatterBehavior = NumberFormatter.Behavior.behavior10_4
formatter.numberStyle = NumberFormatter.Style.currency
formatter.locale = locale
let formattedPrice = formatter.string(from: price)!
let currencySymbolsOnly = formattedPrice.replacingOccurrences(of: "0", with: "")
allCurrencySymbols.append(currencySymbolsOnly)
}
var set = Set<Character>()
let allCurrencySymbolsMinusDuplicates = String(allCurrencySymbols.characters.filter{ set.insert($0).inserted } )
print(allCurrencySymbolsMinusDuplicates)
On my Mac, this produces the output…
, ¤KMFCABuRE.‏₪٠٫۰$০₹YDTShN¥H€₺₦L₸rOP£៛၀nG₵денКМأم०UفجقVsk/zł؋Q༠Zد֏رسل₱؜یاoʻmكብርXdjbI₾ع​₽сом₼ت₩f₡¥Wරුeب₭नेरूtإë₴l৳يp₫лвč₮
…which you can use to create your bitmap font. But remember your source font will need to support the characters, too.

Resources