isStringPercentage function

bool isStringPercentage(
  1. String str
)

Returns true if the given str is a string representation of a percentage, false otherwise.

A string is considered a percentage if it:

  • is not empty
  • contains at most one '%' character
  • ends with a '%' character
  • the remaining characters, after removing the '%' character, represent a valid number.

Implementation

bool isStringPercentage(String str) {
  if (str.isEmpty) return false;

  if ('%'.allMatches(str).length > 1) return false;

  final lastChar = str[str.length - 1];

  if (lastChar != '%') return false;

  final isNumber = isStringNumber(str.replaceAll('%', ''));

  if (!isNumber) return false;

  return true;
}