Created
February 26, 2023 20:53
-
-
Save iampato/775660d0f900887707b60936c5c09c44 to your computer and use it in GitHub Desktop.
convert digitis into words
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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