7

How can I convert Persian/Arabic numbers to English in Kotlin? I saw similar qustions in java but It doesn't match my requirement. I want to pass Date as String to web service. when I get Date in devices that uses Persian localized digits are Persian and the server can't convert this String to DateTime. So I need to convert all digits to English. here is the Date that I receive in Devices with Persian Localized:

"۲۰۲۰/۰۸/۲۱"

and these are Persian/Arabic numbers

(۰ -> 0) (۱ -> 1) (۲ -> 2) (۳ -> 3) (۴ -> 4) (۵ -> 5) (۶ -> 6) (۷-> 7) (۸ -> 8) (۹ -> 9)

I need a fun in Kotlin to perform this.

Alireza Barakati
  • 1,016
  • 2
  • 9
  • 23
  • or in fact ... it's a XY problem ... and you should format Date using English locale instead of default ... Why it has so much upvotes? – Selvin Sep 21 '20 at 09:42
  • For information about different numerals see [this Wikipedia article](https://en.wikipedia.org/wiki/Eastern_Arabic_numerals#Numerals). – Mahozad Nov 04 '21 at 15:09

2 Answers2

3

Finally bellow function solved my problem:

fun PersianToEnglish(persianStr: String):String {
            var result = ""
            var en = '0'
            for (ch in persianStr) {
                en = ch
                when (ch) {
                    '۰' -> en = '0'
                    '۱' -> en = '1'
                    '۲' -> en = '2'
                    '۳' -> en = '3'
                    '۴' -> en = '4'
                    '۵' -> en = '5'
                    '۶' -> en = '6'
                    '۷' -> en = '7'
                    '۸' -> en = '8'
                    '۹' -> en = '9'
                }
                result = "${result}$en"
            }
            return result
        }
Alireza Barakati
  • 1,016
  • 2
  • 9
  • 23
2

You can use NumberFormat, providing a proper locale.

//explode date by slash character
var delimiter = "/"
val parts = yourDate.split(delimiter) 

// then you check every element in parts array

NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH);
...
for (int i = 0; i < a.length; ++i) {
    output.println(nf.format(myNumber[i]) + "; ");
}

Reference: NumberFormat documentation, Locale docs

Alfabravo
  • 7,493
  • 6
  • 46
  • 82