Here is a function called paserNumber that converts a string representing a number into an actual JS Number object. It can also accept number strings with fractions (decimal numbers) and Arabic/Persian/English thousands separators. I don't know whether this solution is the best, performance-wise.
function parseNumber(numberText: string) {
return Number(
// Convert Persian (and Arabic) digits to Latin digits
normalizeDigits(numberText)
// Convert Persian/Arabic decimal separator to English decimal separator (dot)
.replace(/٫/g, ".")
// Remove other characters such as thousands separators
.replace(/[^\d.]/g, "")
);
}
const persianDigitsRegex = [/۰/g, /۱/g, /۲/g, /۳/g, /۴/g, /۵/g, /۶/g, /۷/g, /۸/g, /۹/g];
const arabicDigitsRegex = [/٠/g, /١/g, /٢/g, /٣/g, /٤/g, /٥/g, /٦/g, /٧/g, /٨/g, /٩/g];
function normalizeDigits(text: string) {
for (let i = 0; i < 10; i++) {
text = text
.replace(persianDigitsRegex[i], i.toString())
.replace(arabicDigitsRegex[i], i.toString());
}
return text;
}
Note that the parse function is quite forgiving and the number string can be a combination of Persian/Arabic/Latin numerals and separators.
Side note
After getting a Number you can format it back however you want with Number.toLocaleString function:
let numberString = "۱۲۳۴.5678";
let number = parseNumber(numberString);
val formatted1 = number.toLocaleString("fa"); // OR "fa-IR" for IRAN
val formatted2 = number.toLocaleString("en"); // OR "en-US" for USA
val formatted3 = number.toLocaleString("ar-EG"); // OR "ar" which uses western numerals
For more information about formatting numbers, refer to this answer.
TypeError: Object function Number() { [native code] } has no method 'parseLocale'
. No luck searching Mozilla's documentation either. Is that an IE only thing? – YoshiparseLocale
method. – Zapata