Search code examples
javascriptparsingnumber-formatting

JavaScript can't convert Hindi/Arabic numbers to real numeric variables


I'm trying to use a DOM coming from an external source, and in it there are some numeric values in Hindi/Arabic transcription, like "۱۶۶۰", and when I want to convert it into numeric value I get NaN.

What's wrong here?

A small code snippet to be tried:

alert(Number("۱۶۶۰") + ' - ' + Number("1660"));

Solution

  • Well, the Number function does expect the digits 0 to 9 and does not handle arabic ones.

    You will need to take care of that yourself:

    function parseArabic(str) {
      return Number(str
        .replace(/[٠١٢٣٤٥٦٧٨٩]/g, d => d.charCodeAt(0) - 1632) // convert Arabic digits
        .replace(/[۰۱۲۳۴۵۶۷۸۹]/g, d => d.charCodeAt(0) - 1776) // convert Persian digits
      );
    }
    // usage example:
    console.log( parseArabic("۱۶۶۰") )