Home > Enterprise >  How to get the percentage of two given list and return the value as a list in flutter
How to get the percentage of two given list and return the value as a list in flutter

Time:08-25

I have 2 list

List a = [0,2,0]; List b = [0,3,0];

Now I want to create a function to calculate this list and return a list of percentages.

Return [0,67,0]

void main() {
getPercentage();
}

int? getPercentage(){
  
  List<int> a = [0,2,0];
  List<int> b = [0,3,0];
  
  for (int i = 0; i < a.length; i  ) { 
    int percentage = ((a[i]/b[i]*100).toInt());
    return percentage;
  }
}

I tried this.

CodePudding user response:

The issue occurs when the number is divided by 0

You can replace 0 with 1.

List<int>? getPercentage() {
  List<int> a = [0, 2, 0];
  List<int> b = [0, 3, 0];

  List<int> percentage = [];
  for (int i = 0; i < a.length; i  ) {
    int x = a[i] <= 0 ? 1 : a[i];
    int y = b[i] <= 0 ? 1 : b[i];
    final p = (x / y * 100).toInt();
    percentage.add(p);
  }
  return percentage;
}
void main() {
  print(getPercentage()); //[100, 66, 100]
}

CodePudding user response:

The following should work:

void main() {
  getPercentage();
}

List<int> getPercentage(){
  List<int> a = [0,2,0];
  List<int> b = [0,3,0];
  List<int> result = [];

  for (int i = 0; i < a.length; i  ) { 
    int percentage = b == 0 ? 0 : (a[i] / b[i] * 100).toInt();
    result.add(percentage);
  }
  return result;
}

CodePudding user response:

Alternatively use this function for any A/B int list with nan check:

List<int> getPercentage(List<int> ListA, List<int> ListB) {
  int maxLength = min(ListA.length, ListB.length); // check if has same # items
  List<int> result = [];
  for (int i = 0; i < maxLength; i  ) {
    var calc = (ListA[i] / ListB[i]) * 100; // calc % A/B of item i
    calc = (calc).isNaN ? 0 : calc; //check if is nan (divided by zero) return 0
    result.add((calc).toInt()); //add to result list
  }
  return result;
}
  • Related