How to convert latin numbers to arabic in javascript?

Viewed 464

I use a custom function to convert numbers to arabic format like this :

 const numbers = `۰۱۲۳۴۵۶۷۸۹`;
  const convert = (num) => {
    let res = "";
    const str = num.toString();
    for (let c of str) {
      res += numbers.charAt(c);
    }
    return res;
  };

And it works like this :

console.log(convert(123)) // ==> ۱۲۳

The problem occurs when there is a number with decimals and it converts it to arabic format without the decimal dots for example :

console.log(convert(123.9)) // ==> ۱۲۳۹

I expect the output to be ۱۲۳،۹ .

How can I convert numbers with decimals to arabic format with decimal dots included with my function ?

2 Answers

Another way to convert Latin numbers to Arabic by taking care of both the decimal point and the thousands separator is as follows (notice number is passed as a string):

const numLatinToAr=n=>n.replace(/\d/g,d=>"٠١٢٣٤٥٦٧٨٩"[d]).replace(/\./g, "٫");

console.log(numLatinToAr("12345"));
console.log(numLatinToAr("12345.67"));
console.log(numLatinToAr("12,345.67"));

Another Method is to use the toLocaleString() but do not use the country code as this may change in the future

Use the arab numbering system:

console.log((123.93).toLocaleString('ar-u-nu-arab'))
console.log((4578123.93).toLocaleString('ar-u-nu-arab'))

Related