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.
>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]
}