All files / src/lib currency-utils.ts

100% Statements 40/40
91.66% Branches 22/24
100% Functions 5/5
100% Lines 36/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 74 75 76 77 78 79 80 81 82 83 84 85              10x 10x       10x 10x     6x 6x 6x 6x               25x   25x   3x 3x   22x   2x 2x   20x   17x 17x   3x       22x 7x                 16x 16x   14x 14x   12x 12x     16x   3x 3x   3x 3x   4x 4x   2x     12x    
// Currency utilities for Indian Rupee formatting (paise-based)
 
/**
 * Format paise to Indian Rupee string with proper comma grouping
 * e.g., 42000000 → "4,20,000" (Indian lakhs system)
 */
export function formatPaise(paise: number): string {
	const rupees = Math.round(paise / 100);
	return formatRupees(rupees);
}
 
function formatRupees(rupees: number): string {
	const str = String(Math.abs(rupees));
	if (str.length <= 3) return (rupees < 0 ? "-" : "") + str;
 
	// Indian grouping: last 3, then pairs
	const last3 = str.slice(-3);
	const rest = str.slice(0, -3);
	const grouped = rest.replace(/\B(?=(\d{2})+(?!\d))/g, ",");
	return `${(rupees < 0 ? "-" : "") + grouped},${last3}`;
}
 
/**
 * Abbreviate paise to short form
 * e.g., 4200000 → "42K", 42000000 → "4.2L", 120000000 → "1.2Cr"
 */
export function abbreviatePaise(paise: number): string {
	const rupees = Math.round(paise / 100);
 
	if (rupees >= 10000000) {
		// Crores (1Cr = 10,000,000)
		const cr = rupees / 10000000;
		return `${formatAbbr(cr)}Cr`;
	}
	if (rupees >= 100000) {
		// Lakhs (1L = 100,000)
		const l = rupees / 100000;
		return `${formatAbbr(l)}L`;
	}
	if (rupees >= 1000) {
		// Thousands
		const k = rupees / 1000;
		return `${formatAbbr(k)}K`;
	}
	return String(rupees);
}
 
function formatAbbr(value: number): string {
	if (value === Math.floor(value)) return String(value);
	return value.toFixed(1).replace(/\.0$/, "");
}
 
/**
 * Parse currency shorthand input to paise
 * Supports: "4.2L" → 42000000, "42K" → 420000000, "420000" → 42000000000
 * Also supports: "4.2l", "42k", "1.2Cr", "1.2cr"
 */
export function parseCurrencyInput(input: string): number | null {
	const trimmed = input.trim().replace(/,/g, "").replace(/^₹\s*/, "");
	if (!trimmed) return null;
 
	const match = trimmed.match(/^(\d+(?:\.\d+)?)\s*(cr|l|k)?$/i);
	if (!match) return null;
 
	const value = Number.parseFloat(match[1]);
	const unit = (match[2] || "").toLowerCase();
 
	let rupees: number;
	switch (unit) {
		case "cr":
			rupees = value * 10000000;
			break;
		case "l":
			rupees = value * 100000;
			break;
		case "k":
			rupees = value * 1000;
			break;
		default:
			rupees = value;
	}
 
	return Math.round(rupees * 100); // Convert to paise
}