removeUnnecessaryZeros static method

String removeUnnecessaryZeros(
  1. String formatted,
  2. String symbol,
  3. bool leftSymbol
)

Implementation

static String removeUnnecessaryZeros(
    String formatted, String symbol, bool leftSymbol) {
  formatted = leftSymbol ? formatted.split(' ')[1] : formatted.split(' ')[0];
  // Kiểm tra nếu chuỗi có phần thập phân
  if (formatted.contains('.')) {
    // Tách phần nguyên và phần thập phân
    List<String> parts = formatted.split('.');
    String integerPart = parts[0] == '' ? '0' : parts[0];
    String decimalPart =
        parts[1].replaceAll(RegExp(r'\D'), ''); // Bỏ các ký tự không phải số

    // Loại bỏ các chữ số 0 thừa ở cuối phần thập phân, nhưng giữ lại số khác 0
    decimalPart = decimalPart.replaceAll(RegExp(r'0+$'), '');

    // Nếu phần thập phân sau khi loại bỏ toàn là 0, chỉ trả về phần nguyên
    if (decimalPart.isEmpty) {
      formatted = integerPart;
    } else {
      formatted = '$integerPart.$decimalPart';
    }
  }
  return symbol != ''
      ? leftSymbol
          ? '$symbol $formatted'
          : '$formatted $symbol'
      : formatted;
}