toWords method
Converts the integer to words (supports up to 999,999,999,999)
Implementation
String toWords() {
if (this == 0) return 'zero';
final units = [
'',
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
'eleven',
'twelve',
'thirteen',
'fourteen',
'fifteen',
'sixteen',
'seventeen',
'eighteen',
'nineteen',
];
final tens = [
'',
'',
'twenty',
'thirty',
'forty',
'fifty',
'sixty',
'seventy',
'eighty',
'ninety',
];
final scales = ['', 'thousand', 'million', 'billion'];
String convertLessThanThousand(int num) {
if (num == 0) return '';
if (num < 20) return units[num];
if (num < 100) {
return tens[num ~/ 10] + (num % 10 != 0 ? '-${units[num % 10]}' : '');
}
return '${units[num ~/ 100]} hundred'
'${num % 100 != 0 ? ' and ${convertLessThanThousand(num % 100)}' : ''}';
}
int absNum = this.abs(); // Handle negative numbers
String result = '';
int scaleIndex = 0;
while (absNum > 0) {
int chunk = absNum % 1000;
if (chunk > 0) {
String chunkWords = convertLessThanThousand(chunk);
if (scaleIndex > 0 && chunkWords.isNotEmpty) {
chunkWords += ' ${scales[scaleIndex]}';
}
result = '$chunkWords ${result.trim()}';
}
absNum ~/= 1000;
scaleIndex++;
}
return (this < 0 ? 'negative ' : '') + result.trim();
}