Action

Sum of all Numbers in Draft/Selection

Posted by Chris Grieser (armenaton), Last update about 1 month ago

UPDATES

about 1 month ago

  • now also works on negative numbers
  • copies reuslt to the clipboard
  • shows result in notification instead of appending
show all updates...

about 1 month ago

  • now also works on negative numbers
  • copies reuslt to the clipboard
  • shows result in notification instead of appending

about 1 month ago

  • now also works on negative numbers
  • copies reuslt to the clipboard
  • shows result in notification instead of appending

Calculates the sum of all numbers in the selection. If there is no selection, the entire draft is used as input.

The sum is then displayed as notification & copied to the clipboard.

Works with “.” or “,” as decimal seperators. Also supports with negative numbers, enabling the correct parsing of sequences like 2-4+3 as well.

Caveats: This action does not work with any kind of thousand seperator (“.”, “,”, or space), as they would introduce ambigious cases.

Steps

  • script

    draft.saveVersion();
    
    //gets selection, if no seleciton, gets draft
    if (editor.getSelectedText() == "") {
    	var textToCheck = draft.content;
    } else {
    	var textToCheck = editor.getSelectedText();
    }
    
    //match all numbers in text
    let digitMatches = textToCheck.match(/-?\d+(?:[,|\.]\d+)?/gm);
    
    //addition of all numbers
    var sum = 0;
    var commaAsSep = false;
    digitMatches.forEach(numberAsString => {
    	let numberToAdd = parseFloat (numberAsString);
    	if (numberAsString.includes (",")){
    		commaAsSep = true;
    		numberToAdd = parseFloat (numberAsString.replace (",","."));
    	}
    	sum = sum + numberToAdd;
    });
    
    // Stringify sum, using "," as seperator when it was used
    let sum_string = String(sum);
    if (commaAsSep == true){
    	sum_string = sum_string.replace (".",",");
    }
    
    // Copy to Clipboard
    app.setClipboard(sum_string);
    app.displaySuccessMessage("∑ = " + sum_string);
    
    

Options

  • After Success Default , Tags: calculation
    Notification Error
    Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.