Google Sheets – How to Split, Trim, and Sum Numbers in Text Cells

google sheets

I have a series of cells in a Google Spreadsheet containing string such as:

A1 = "X5.1 Y4.3 Z2.8"
B1 = "X2.5 Y1.9 Z4.8"
C1 = "X6.2 Y1.9 Z3.4"

I need to get the sum of all the numbers that appear inside the strings. In other words, to have a formula which will effectively sum 5.1+4.3+2.8+2.5+1.9+4.8+6.2+1.9+3.4 .

The number of cells to be summed in such a way is dynamic, and typically much more than 3.

Is there way to achieve this elegantly?

Best Answer

If you have a row of data like A1:F1 you could use this formula in excel

=SUMPRODUCT((0&MID(A1:F1,{2;7;12;17;22},3))+0)

or this in google-spreadsheets

=arrayformula(SUM((0&MID(A1:F1,{2;7;12;17;22},3))+0))

That assumes each number is 3 characters like 3.5 and allows for up to 5 numbers per cell - you can extend the {2;7;12;17;22} part if there might be more than 5 per cell - or for high numbers that part can be automated based on cell length.

If you have a column of data like A1:A10 then the separators in {2;7;12;17;22} need to change to commas so that would be like this in excel

=SUMPRODUCT((0&MID(A1:A10,{2,7,12,17,22},3))+0)

or this in google-spreadsheets

=arrayformula(SUM((0&MID(A1:A10,{2,7,12,17,22},3))+0))

blank cells are allowed in the data so you could make that a larger range for expansion purposes.

Explanation:

If A1 contains this string X5.1 Y4.3 Z2.8 then

=MID(A1,{2,7,12,17,22},3)

will give you this "array"

{"5.1","4.3","2.8","",""}

Notice that the values are included in quotes which means they are text values (MID function like LEFT and RIGHT etc. always returns text values) so we need to convert these text strings to numbers before they can be summed - one way to convert is to do a mathematical operation on that array that won't change the values, e.g. *1 or +0. If we use the latter, though, we get this:

{"5.1","4.3","2.8","",""}+0 = {5.1,4.3,2.8,#VALUE!,#VALUE!}

applying +0 to the non-numeric blank [""] values gives #VALUE! error....which is a problem if we want to sum the results.......so, before adding zero we can concatenate a zero to the front of each result, e.g. using

=0&MID(A1,{2,7,12,17,22},3)

gives the result

={"05.1","04.3","02.8","0","0"}

concatenating a zero to the front of each number won't chage the value of the numeric values but converts the blanks to zeroes, so now when zero is added we get no errors, just:

{5.1,4.3,2.8,0,0}

which can be summed without error.

Extending the range to A1:A10 simply means that the resultant array is 10x5 rather than 1x5 - everything else works the same way.......