Skip to content

Instantly share code, notes, and snippets.

@iampato
Created February 26, 2023 20:53
Show Gist options
  • Save iampato/775660d0f900887707b60936c5c09c44 to your computer and use it in GitHub Desktop.
Save iampato/775660d0f900887707b60936c5c09c44 to your computer and use it in GitHub Desktop.
convert digitis into words
library digits_to_words;
class DigitsToWords {
static const List<String> _units = [
"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
];
static const List<String> _tens = [
"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
];
static const List<String> _teens = [
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen"
];
static const List<String> _ordersOfMagnitude = [
"", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion",
"sextillion", "septillion", "octillion", "nonillion", "decillion"
];
static String convert(int number) {
if (number == 0) {
return "zero";
}
String result = "";
int i = 0;
while (number > 0) {
int hundreds = number % 1000;
if (hundreds != 0) {
result = "${_convertHundreds(hundreds)} ${_ordersOfMagnitude[i]} $result";
}
i++;
number ~/= 1000;
}
return result.trim();
}
static String _convertHundreds(int number) {
String result = "";
int digit = number ~/ 100;
if (digit != 0) {
result = "${_units[digit]} hundred";
}
digit = (number % 100) ~/ 10;
if (digit == 1) {
result += " ${_teens[number % 10]}";
} else {
if (digit != 0) {
result += " ${_tens[digit]}";
}
digit = number % 10;
if (digit != 0) {
result += " ${_units[digit]}";
}
}
return result.trim();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment