translateAmountToVietWords static method
String
translateAmountToVietWords(
- String numberToTranslate
)
Implementation
static String translateAmountToVietWords(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 'số không';
}
final List<String> units = [
'',
'một',
'hai',
'ba',
'bốn',
'năm',
'sáu',
'bảy',
'tám',
'chín',
'mười',
'mười một',
'mười hai',
'mười ba',
'mười bốn',
'mười lăm',
'mười sáu',
'mười bảy',
'mười tám',
'mười chín'
];
final List<String> tens = [
'',
'',
'hai mươi',
'ba mươi',
'bốn mươi',
'năm mươi',
'sáu mươi',
'bảy mươi',
'tám mươi',
'chín mươi'
];
final List<String> powersOfTen = ['', 'nghìn', 'triệu', 'tỷ', 'nghìn tỷ'];
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]} trăm');
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 != "số không") {
return "${result.join(' ')} điểm $decimalResult";
} else {
return result.join(' ');
}
}