Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading