Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to another locale in java

Tags:

java

locale

I need to convert Arabic/Persian Numbers to its English equal (for example convert "۲" to "2")

How can I do this?

like image 493
Ariyan Avatar asked Mar 15 '11 18:03

Ariyan


2 Answers

I suggest you have a ten digit lookup String and replace all the digits one at a time.

public static void main(String... args) {
    System.out.println(arabicToDecimal("۴۲"));
}
//used in Persian apps
private static final String extendedArabic = "\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9";

//used in Arabic apps
private static final String arabic = "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669";

private static String arabicToDecimal(String number) {
    char[] chars = new char[number.length()];
    for(int i=0;i<number.length();i++) {
        char ch = number.charAt(i);
        if (ch >= 0x0660 && ch <= 0x0669)
           ch -= 0x0660 - '0';
        else if (ch >= 0x06f0 && ch <= 0x06F9)
           ch -= 0x06f0 - '0';
        chars[i] = ch;
    }
    return new String(chars);
}

prints

42

The reason for using the strings as a lookup is that other characters such as . - , would be left as is. In fact a decimal number would be unchanged.

like image 165
Peter Lawrey Avatar answered Oct 23 '22 04:10

Peter Lawrey


I achived this by java.math.BigDecimal Class, Below is the code snippet

String arabicNumerals = "۴۲۴۲.۴۲";
String englishNumerals = new BigDecimal(arabic).toString();
System.out.println("Number In Arabic : "+arabicNumerals);
System.out.println("Number In English : "+englishNumerals);

Result

Number In Arabic : ۴۲۴۲.۴۲
Number In English : 4242.42

NB: The above code will not work if there are any characteors other than numeric digits in arabicNumerals, for example: ۴,۲۴۲.۴۲ will result in a java.lang.NumberFormatException, so you may remove other characters using Character.isDigit(char ch) in another logic and use the above code. All normal cases are working.

like image 27
Navas Basheer Avatar answered Oct 23 '22 03:10

Navas Basheer