Updated: See the notes before the download for information in internationalization.

Here’s a quick System Service for OS X that finds all the numbers in selected text and adds them together. I find myself making lists of numbers in Markdown quite a bit, and often just want to add them all together. That’s what this does.

It works with decimals and currency symbols (including “,” as a decimal separator) and ignores all other text. There can be more than one number on a line. The output will have as many decimal places as needed to match what’s found in the text. Negative numbers work as well.

The output doesn’t replace your existing text; it appends the total number after a new line below the selection. I’ve toyed with making a Markdown Table Calculator that lets you use spreadsheet-style “SUM” fields to get row and column totals, but that’s still just an idea. This is just a quick and dirty solution.

If you’re interested in the nitty gritty, here’s the script from inside the Service:

total_numbers.rbraw
"
#!/usr/bin/ruby

decimal = "."
separator = ","

if RUBY_VERSION.to_f > 1.9
  Encoding.default_external = Encoding::UTF_8
  Encoding.default_internal = Encoding::UTF_8
  input = STDIN.read.force_encoding('utf-8')
else
  input = STDIN.read
end

def esc(char)
  return "\\#{char}"
end

total = 0
places = 0

input.scan(/(\-?[\d#{esc(separator)}]+(#{esc(decimal)}\d+)?)\b/).each {|x|
  total += x[0].gsub(/#{esc(separator)}/,'').sub(/#{esc(decimal)}/,'.').to_f
  places = x[1].length - 1 if x[1] && x[1].length.to_i > places + 1
}

puts input.chomp
out = "\n%.#{places.to_i}f" % total
puts out.sub(/\./,decimal)

Download, unzip, and double click to install. Just select some text containing numbers, right click, and choose “Total Numbers” to get the result.

Update: The Service now handles commas in numbers for standard decimal notation, and you can change the separator and decimal delimiter at the top of the script. Open the workflow in Automator and you’ll see two variables at the very top where you can define these. Use this to change the decimal delimiter to “,” for example.

Total Numbers Service v1.1

An OS X Service to toal all numbers found in selected text

Published 04/10/14.

Updated 04/10/14. Changelog

DonateMore info…