QGIS – Summing Numbers Separated by Commas in String Field

fields-attributesqgisstringsummarizing

In QGIS, I have a column separated by comma (shown by column "lengths"). I want to sum up elements in it for each row. The column is a text field string.

attribute table

Best Answer

You can use arrays in fieldcalculator for this:

array_sum(array_foreach(string_to_array("lengths",','),to_real(@element)))
  1. Turn the string into an array
  2. Iterate over the array and convert the string elements to an integer or double
  3. Build the sum (array_sum() available since QGIS 3.18)

To catch errors on invalid "numbers", you can use try():

array_sum(array_foreach(string_to_array("lengths",','),try(to_real(@element),0)))