Timitrov
Timitrov

Reputation: 221

Round list of doubles

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.

Upvotes: 0

Views: 145

Answers (1)

tareq albeesh
tareq albeesh

Reputation: 1861

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);
 }

Upvotes: 1

Related Questions