0

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.

Timitrov
  • 211
  • 1
  • 3
  • 14
  • Make sure to understand that [rounding `double`s to a number of decimal digits is inherently problematic](https://stackoverflow.com/a/68980598/). – jamesdlin Mar 13 '22 at 10:32

1 Answers1

1

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);
 }
tareq albeesh
  • 1,701
  • 2
  • 10
  • 13