formatAmountInput function

String? formatAmountInput(
  1. String input
)

Writes back an amount typed in any form parseAmount accepts, for showing next to the field ("= Rs. 150,000"): Rs., international grouping, and paisa only when there are any (Rs. 1,234.50). Returns null when parseAmount does; it never throws.

E.g. "Rs. 150,000" for "1.5 lakh", or null.

Implementation

String? formatAmountInput(String input) {
  final parsed = parseAmount(input);
  if (parsed == null) return null;
  final cents = jsRound(parsed.value * 100).toInt();
  final rupees = (cents ~/ 100).toString();
  final out = StringBuffer();
  for (var i = 0; i < rupees.length; i++) {
    if (i > 0 && (rupees.length - i) % 3 == 0) out.write(',');
    out.write(rupees[i]);
  }
  final paisa = cents % 100;
  return 'Rs. $out${paisa != 0 ? '.${paisa.toString().padLeft(2, '0')}' : ''}';
}