I have an english string that may or may not have numbers. But i want those numbers to be printed on screen as Persian numbers.
For example if NSString *foo =
I'm afraid there is no other way than replacing them.
e.g.:
str =[str stringByReplacingOccurrencesOfString:@"0" withString:@"۰"];
.
.
.
Swift 5 and newer
if you want to make a subclass of UILabel:
class LocalizedNumbersLabel: UILabel {
override var text: String? {
didSet {
if let text = text {
let numbersDictionary : Dictionary = ["0" : "۰","1" : "۱", "2" : "۲", "3" : "۳", "4" : "۴", "5" : "۵", "6" : "۶", "7" : "۷", "8" : "۸", "9" : "۹", "." : ","]
var str = text
for (key,value) in numbersDictionary {
str = str.replacingOccurrences(of: key, with: value)
}
if(str != self.text){
self.text = str
}
} else {
}
}
}
}
In swift 5
func getNumerals(num: Int) -> String {
if getLanguage() == "ar" // You can set locale of your language
{
let number = NSNumber(value: num)
let format = NumberFormatter()
format.locale = Locale(identifier: "ar") // You can set locale of your language
let formatedNumber = format.string(from: number)
return formatedNumber!
} else {
return "\(num)"
}
}
with the following extension, you can do it:
extension String {
private static let formatter = NumberFormatter()
func clippingCharacters(in characterSet: CharacterSet) -> String {
components(separatedBy: characterSet).joined()
}
func convertedDigitsToLocale(_ locale: Locale = .current) -> String {
let digits = Set(clippingCharacters(in: CharacterSet.decimalDigits.inverted))
guard !digits.isEmpty else { return self }
Self.formatter.locale = locale
let maps: [(original: String, converted: String)] = digits.map {
let original = String($0)
guard let digit = Self.formatter.number(from: String($0)) else {
assertionFailure("Can not convert to number from: \(original)")
return (original, original)
}
guard let localized = Self.formatter.string(from: digit) else {
assertionFailure("Can not convert to string from: \(digit)")
return (original, original)
}
return (original, localized)
}
var converted = self
for map in maps { converted = converted.replacingOccurrences(of: map.original, with: map.converted) }
return converted
}
}
"سلام 12345".convertedDigitsToLocale(Locale(identifier: "FA")) /* سلام ۱۲۳۴۵ */
"Hello ۱۲۳۴۵".convertedDigitsToLocale(Locale(identifier: "EN")) /* Hello 12345 */