fatCop
fatCop

Reputation: 2576

How to convert Bengali Unicode numbers?

How can I convert Bengali Unicode numerical values (০,১,২,৩,...,৮,৯) to (0,1,2,3,...,8,9) in Java?

Upvotes: 3

Views: 1507

Answers (5)

Stephan
Stephan

Reputation: 43053

Try this:

/**
 *
 * Convert a bengali numeral to its arabic equivalent numeral.
 *
 * @param bengaliNumeral bengali numeral to be converted
 *
 * @return the equivalent Arabic numeral
 * @see #bengaliToInt
 */
public static char bengaliToArabic(char bengaliNumeral) {
    return (char) (bengaliNumeral - '০' + '0');
}

public static int bengaliToInt(char bengaliNumeral) {
    return Character.getNumericValue(bengaliNumeral);
}

DEMO

SAMPLE CODE

System.out.format("bengaliToArabic('১') == %s // char\n", bengaliToArabic('১'));
System.out.format("bengaliToInt('১')    == %s // int\n", bengaliToInt('১'));

OUTPUT

bengaliToArabic('১') == 1 // char
bengaliToInt('১')    == 1 // int

Upvotes: 3

Rohan
Rohan

Reputation: 179

Use -
Character.getNumericValue('০').
It will work irrespective of the language because it uses the unicode of the character for conversion

Upvotes: 3

Andy Turner
Andy Turner

Reputation: 140494

Use Character.getNumericValue to get the integer value associated with a character:

System.out.println(Character.getNumericValue('০'));
System.out.println(Character.getNumericValue('১'));
// etc.

Output:

0
1

Ideone demo

The advantage over other approaches here is that this works for any numeric chars, not just Bengali.

Upvotes: 7

Elias Mårtenson
Elias Mårtenson

Reputation: 3885

A lot of solutions here suggest to simply subtract the Unicode value for the character to get the numerical value. This works, but will only work if you know for a fact that the number is in fact a Bengali number. There are plenty of other numbers, and Java provides a standardised way to handle this using Character.getNumericValue() and Character.digit():

String s = "123০১২৩৪৫৬৭৮৯";
for(int i = 0 ; i < s.length() ; i++) {
  System.out.println(Character.digit(ch, 10));
}

This will work with not only Bengali numbers, but with numbers from all languages.

Upvotes: 2

Tunaki
Tunaki

Reputation: 137184

A simple solution subtract the value of '০' to the rest, since they are contiguous in the Unicode table, and add '0':

public static void main(String[] args) {
    char[] bengaliDigits = {'০','১','২','৩','৪','৫','৬','৭','৮','৯'};
    for (char bengaliDigit : bengaliDigits) {
        char digit = (char) (bengaliDigit - '০' + '0');
        System.out.print(digit);
    }
}

This will print 0123456789.

Upvotes: 4

Related Questions