Exercise 7: Format Currency (Indian Format)
Problem Statement
Create a function `formatCurrency(amount)` that converts a number to Indian currency format.
Example: 1234567 → "12,34,567"
Note: Indian numbering system uses lakhs/crores.
Sample Output:
formatCurrency(1234567) => "12,34,567" formatCurrency(10000000) => "1,00,00,000" formatCurrency(-5000) => "5,000"
Solution
const formatCurrency = (amount) => {
const n = Number(amount);
if (!Number.isFinite(n)) return "0";
return Math.abs(n).toLocaleString("en-IN");
};Explanation
Overall Goal:
- Number ko Indian currency format me convert karna (lakhs/crores).
- Thousand separators add karna (12,34,567 format).
Line 1: Function header
const formatCurrency = (amount) => {
Line 2: Convert to number
const n = Number(amount);- Input ko number me convert.
Line 3: Validation
if (!Number.isFinite(n)) return "0";- Invalid number ho to "0" return.
Line 4: Format with locale
return Math.abs(n).toLocaleString("en-IN");Math.abs(n)→ negative numbers ko positive me convert..toLocaleString("en-IN")→ Indian locale format:1234567→"12,34,567"(lakhs format).10000000→"1,00,00,000"(crores format).
Real world:
- E-commerce: product prices display.
- Banking apps: account balance formatting.
- Invoice generation: amount formatting.