translateAmountToChineseWords static method

String translateAmountToChineseWords(
  1. String numberToTranslate
)

Implementation

static String translateAmountToChineseWords(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 '零';
  }

  final List<String> units = [
    '',
    '一',
    '二',
    '三',
    '四',
    '五',
    '六',
    '七',
    '八',
    '九',
    '十',
    '十一',
    '十二',
    '十三',
    '十四',
    '十五',
    '十六',
    '十七',
    '十八',
    '十九'
  ];

  final List<String> tens = [
    '',
    '',
    '二十',
    '三十',
    '四十',
    '五十',
    '六十',
    '七十',
    '八十',
    '九十'
  ];

  final List<String> powersOfTen = ['', '千', '百万', '十亿', '万亿'];

  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]} 百');
        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 = _decimalPointTranslate(decimal.toString());

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