translateAmountToEngWords static method

String translateAmountToEngWords(
  1. String numberToTranslate
)

Implementation

static String translateAmountToEngWords(String numberToTranslate) {
  int number = 0;
  int decimal = 0;

  if (numberToTranslate.contains('.')) {
    number = int.parse(
        numberToTranslate.split('.')[0].toString().replaceAll(',', ''));

    decimal = int.parse(
        numberToTranslate.split('.')[1].toString().replaceAll(',', ''));
  } else {
    number = int.parse(numberToTranslate.replaceAll(',', ''));
  }

  if (number == 0) {
    return 'zero';
  }

  final List<String> units = [
    '',
    'one',
    'two',
    'three',
    'four',
    'five',
    'six',
    'seven',
    'eight',
    'nine',
    'ten',
    'eleven',
    'twelve',
    'thirteen',
    'fourteen',
    'fifteen',
    'sixteen',
    'seventeen',
    'eighteen',
    'nineteen'
  ];

  final List<String> tens = [
    '',
    '',
    'twenty',
    'thirty',
    'forty',
    'fifty',
    'sixty',
    'seventy',
    'eighty',
    'ninety'
  ];

  final List<String> powersOfTen = [
    '',
    'thousand',
    'million',
    'billion',
    'trillion'
  ];

  List<String> result = [];
  int powerIndex = 0;

  while (number > 0) {
    int chunk = number % 1000;
    if (chunk != 0) {
      List<String> chunkWords = [];
      if (chunk >= 100) {
        chunkWords.add('${units[chunk ~/ 100]} hundred');
        chunk %= 100;
      }
      if (chunk >= 20) {
        chunkWords.add(tens[chunk ~/ 10]);
        chunk %= 10;
      }
      if (chunk > 0) {
        if (chunk < 20) {
          chunkWords.add(units[chunk]);
        } else {
          chunkWords.add(tens[chunk ~/ 10]);
          chunk %= 10;
          if (chunk > 0) {
            chunkWords.add(units[chunk]);
          }
        }
      }
      // Join the words for this chunk and add them to the result list
      result.insert(0, chunkWords.join(' '));
    }

    // Add the power of ten (e.g., thousand, million) to the result if necessary
    if (powerIndex > 0 && result.isNotEmpty) {
      result.insert(1, powersOfTen[powerIndex]);
    }

    // Move to the next group of three digits
    number ~/= 1000;
    powerIndex++;
  }

  //translate decimal
  var decimalResult = _decimalPointTranslateEng(decimal.toString());

  // Join the words in the result list with spaces to form the final representation
  if (decimalResult != "" && decimalResult != "zero") {
    return "${result.join(' ')} point $decimalResult";
  } else {
    return result.join(' ');
  }
}