Sometime in web development, you may want to allow users change the value in indian and international format. It can be like 10,00,000 in indian format and 1,000,000 in international format. In this case, the below code can be useful for developers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
<div> <label for="numberInput">Enter a number:</label> <input type="text" id="numberInput"> </div> <div> <label for="formatStyle">Format style:</label> <select id="formatStyle"> <option value="indian">Indian</option> <option value="international">International</option> </select> </div> <button onclick="formatDemo()">Format</button> <div id="result"></div> <script> function formatNumber(number, style) { // Remove any existing commas and trim whitespace number = number.toString().replace(/,/g, '').trim(); // Check if the number is valid if (!number.match(/^-?\d*\.?\d+$/)) { return "Invalid number"; } // Split into integer and decimal parts let parts = number.split('.'); let integerPart = parts[0]; let decimalPart = parts.length > 1 ? '.' + parts[1] : ''; // Handle negative numbers let sign = ''; if (integerPart.startsWith('-')) { sign = '-'; integerPart = integerPart.substring(1); } // Format the integer part based on the style let formattedInteger; if (style === 'indian') { formattedInteger = formatIndian(integerPart); } else { // International formatting (default) formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ","); } return sign + formattedInteger + decimalPart; } function formatIndian(integerPart) { // Indian numbering system: // First 3 digits from right, then 2 digits groups if (integerPart.length <= 3) { return integerPart; } let lastThree = integerPart.slice(-3); let otherDigits = integerPart.slice(0, -3); // Add commas for 2-digit groups return otherDigits.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + ',' + lastThree; } function formatDemo() { const input = document.getElementById('numberInput').value; const style = document.getElementById('formatStyle').value; const result = formatNumber(input, style); document.getElementById('result').textContent = Formatted number: ${result}; } </script> |
When you execute the above code, you will get a select dropdown and button. When you select the indian format and click the button, it change the value into indian format. If you select the international format in the dropdown and click the button, you will get the value in international format.