Nitneuq
Nitneuq

Reputation: 5012

How to make sum of double value in a string in flutter?

Hello I have a simple string formatted like that (2.0, 1.0, 1.0, 3.0, 5.0)

I don't found how to simply make a sum of each value 2.0+1.0+1.0+3.0+5.0 = 11.0

Thank you

Upvotes: 0

Views: 565

Answers (1)

Jigar Patel
Jigar Patel

Reputation: 5423

One way you can do is like this.

  String str = "(2.0, 1.0, 1.0, 3.0, 5.0)";
  str = str.replaceAll("(","");
  str = str.replaceAll(")","");
  List<String> strDoubles = str.split(", ");
  
  double sum = 0;
  strDoubles.forEach((String item){
    sum = sum + double.parse(item);
  });
  print(sum);       //<-- prints 12

Upvotes: 2

Related Questions