3

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

Tunaki
  • 132,869
  • 46
  • 340
  • 423
fatCop
  • 2,556
  • 10
  • 35
  • 57
  • 1
    Possible duplicate of [this](http://stackoverflow.com/questions/5316131/convert-string-to-another-locale-in-java) – Richard May 04 '16 at 07:57

5 Answers5

7

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
4

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.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
3

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
Stephan
  • 41,764
  • 65
  • 238
  • 329
3

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

Rohan
  • 179
  • 2
  • 3
2

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.

Elias Mårtenson
  • 3,820
  • 23
  • 32