Home > front end >  Round list of doubles
Round list of doubles

Time:03-13

I have a list of many double elements which contains for example the following elements: [1.95, 1.986, 1.9602, 2.0477,...

I tried to use this code to round the elements to two numbers of decimal places:

List<double> listMax = List.from(data_snap()['animals']); //from Firebase
for (var value in listMax) {
  value = roundDouble(value,2);
}

double roundDouble(double value, int places){
  double mod = pow(10.0, places);
  return ((value * mod).round().toDouble() / mod);
 }

And as an alternative:

listMax.forEach((element) => roundDouble(element,2));

But both codes are not successful.

CodePudding user response:

in your codes you are changing the value of a temp variable, to change the value in the list your code should be like:

List<double> listMax = List.from(data_snap()['animals']); //from Firebase
for(int i =0 ;i<listMax.length;i  ){
  listMax[i]= roundDouble(listMax[i],2);
}

double roundDouble(double value, int places){
  double mod = pow(10.0, places);
  return ((value * mod).round().toDouble() / mod);
 }
  • Related