Home > database >  How do I calculate a percentage based on a List of booleans?
How do I calculate a percentage based on a List of booleans?

Time:03-11

I have a list of booleans here:

List<bool> list = [false, false, false, false];

Using that as an example, if I were to find the percentage of values that are true, it would be 0%.

Using another example:

List<bool> list = [true, true, false, false];

The percentage of values that are true would be 50%.

I was able to find something similar to what I need here: Flutter - Count List with bool which works.

However, the calculations to percentages are a little lost on me.

CodePudding user response:

It's basically just the number of true elements divided by the total number of elements.

void main() {
  List<bool> list = [true, true, false, false];
  double percent = list.where((v) => v).length / list.length;
  String percentString = '${(percent * 100).round()}%';
  print(percent);
  print(percentString);
}

CodePudding user response:

You should probably do something like :

  int trueValues = list.fold(0, (acc, val) => val ?   acc : acc);
  double truePercent = trueValues / list.length;

count the number of 'true' value and divide it by the list size (total number of values)

  • Related