Search code examples
javaandroidnumberformatexceptionarabic-support

Integer.valueOf Arabic number works fine but Float.valueOf the same number gives NumberFormatException


Using Arabic number Integer.valueOf("۱") returns integer 1 but Float.valueOf("۱") or Float.parseFloat("۱") throws NumberFormatException while it won't throw any exceptions if you use English number Float.valueOf("1"), is it a bug in java or there's some explanation?

How can I parse such a number?

I'm working in android environment;


Solution

  • It seems that Float.parseFloat() does not support Eastern-Arabic numbers. Alternatively, you can use NumberFormat class:

    Locale EASTERN_ARABIC_NUMBERS_LOCALE = new Locale.Builder()
                                                     .setLanguage("ar")
                                                     .setExtension('u', "nu-arab")
                                                     .build();
    float f = NumberFormat.getInstance(EASTERN_ARABIC_NUMBERS_LOCALE)
                          .parse("۱٫۵")
                          .floatValue();
    System.out.println(f);
    

    OUTPUT:

    1.5