Введение
Попрощайтесь с ограничениями стандартного JavaScript toLocaleString, когда дело доходит до представления валюты в индийских рупиях (INR)! Представляем революционный полифилл convertToIndianNumberSystem, ваш шлюз для простого форматирования числовых значений в очаровательной индийской системе цифр. Воспользуйтесь удобством группировки таких единиц, как тысячи, лакхи и кроры, чтобы создать привлекательный дисплей валюты.
Понимание функции
Предоставленная функция JavaScript, convertToIndianNumberSystem, принимает числовое значение в качестве входных данных и возвращает соответствующее строковое представление в индийской системе цифр. Давайте пройдемся по коду, чтобы понять принцип его работы.
const convertToIndianNumberSystem = (num = 0) => {
// Step 1: Convert the number to a string and extract the decimal part (if present)
const inputStr = num.toString();
const [numStr, decimal] = inputStr.split(".");
// Step 2: Handle the decimal part, keeping only two decimal places
const formattedDecimal = decimal ? `.${decimal.substring(0, 2)}` : "";
// Step 3: Define regular expressions for matching number patterns in the Indian digit system
const croreRegex = /^(\d+)(\d{2})(\d{2})(\d{3})$/;
const lakhRegex = /^(\d{1,2})(\d{2})(\d{3})$/;
const thousandRegex = /^(\d{1,2})(\d{3})$/;
let match;
// Step 4: Try matching the number with the crore pattern first
if (croreRegex.test(numStr)) {
match = numStr.match(croreRegex);
match.shift(); // Remove the first element (entire matched string)
return `${match.join(",")}${formattedDecimal} Crores`;
}
// Step 5: If not matched with the crore pattern, try matching with the lakh pattern
if (lakhRegex.test(numStr)) {
match = numStr.match(lakhRegex);
match.shift(); // Remove the first element (entire matched string)
return `${match.join(",")}${formattedDecimal} Lakhs`;
}
// Step 6: If not matched with the lakh pattern, try matching with the thousand pattern
if (thousandRegex.test(numStr)) {
match = numStr.match(thousandRegex);
match.shift(); // Remove the first element (entire matched string)
return `${match.join(",")}${formattedDecimal} Thousands`;
}
// Step 7: If no pattern matches, return the original number with decimal (if present)
return `${numStr}${formattedDecimal}`;
};
Использование и примеры
console.log(convertToIndianNumberSystem(12345678)); // Output: 1,23,45,678 Crores console.log(convertToIndianNumberSystem(9876543)); // Output: 98,76,543 Lakhs console.log(convertToIndianNumberSystem(12345.67)); // Output: 12,345.67 Thousands console.log(convertToIndianNumberSystem(1000)); // Output: 1,000 Thousands console.log(convertToIndianNumberSystem(123.456)); // Output: 123.45 console.log(convertToIndianNumberSystem()); // Output: 0
Заключение
В этой статье мы успешно написали функцию JavaScript для преобразования числовых значений в индийскую систему цифр. Функция точно преобразует числовые значения в их соответствующее представление в тысячах, лакхах и крорах. Вы можете легко интегрировать эту функцию в свои проекты JavaScript, чтобы эффективно обрабатывать числа в индийской системе счисления.