Search code examples
javascriptreactjsnumbersdecimalnumber-formatting

How to convert latin numbers to arabic in javascript?


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 ?


Solution

  • Try toLocaleString()

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

    console.log((123.9).toLocaleString('ar-AE'))

    Edit:

    with toLocaleString options

    (123.9872512).toLocaleString("ar-AE", {
      useGrouping: false,
      maximumSignificantDigits: 10
    })