Notes

  • In v2.31.1, added math_textAttr.
  • In v2.28.0
    • Fix documentation and processing of math_prefix and math_suffix options. See issue #1305.
    • Remove math_prefix content prior to parsing table cell values.
    • Added "Methods" section & more mask examples.
  • In v2.27.0
    • Added check for data-math-target attribute which allows you to target an element inside the table cell. See the Attribute Settings > Targeting cell content section below.
    • Added a math_debug option which when true, enables debug logging of only the math widget.
    • The math widget no longer uses "update" after recalculating cell values. Instead it uses "updateCache" to remove the need to resort and update the other widgets.
  • In v2.25.0
    • math_rowFilter can now be overridden by the row's data-math-filter attribute.
    • Lots of optimizations!
      • On initialization, only tbody cells with a rowspan or colspan are now processed and only get a "data-column" set if the internal cellIndex doesn't match the calculated cell index.
      • Initial calculation is no longer performed three times in a row
      • The cache is now only updated if cell content inside of a sortable tbody was modified.
      • These changes should improve performance and reduce lag after initialization and updating the table (see issue #1048.

Older Notes

  • In v2.24.6, added math_rowFilter option.
  • In v2.24.0
    • Added "below" type of data-gathering (see Attribute Settings below for more info). See pull #873; thanks to LvLynx!.
    • Added math_none option which allows customizing the text added to a cell when there are no matching math elements (.
  • In v2.22.0,
    • Fixed an issue with a sum column encountering a cell without a defined "data-math" attribute returning an empty string instead of zero. See issue #873.
    • Fixed a javascript error occurring on empty tables & now all updates will reapply column indexing to tbody cells - I know this isn't ideal as it would be slow on larger tables.
  • In v2.19.1, added math_event option & fixed an issue with event unbinding in jQuery version < 1.9.
  • In v2.17.1,
    • Values added to the data-attribute set by the textAttribute option will now be used in the calculation instead of the actual cell content.
    • The Grand Total cells now shows a higher precision value to emphasize this point.
  • In v2.16.4, added:
    • Two new options: math_prefix and math_suffix, which will be added before or after the prefix or suffix, respectively.
    • Added "Mask Examples" section with examples, and how to use the $.tablesorter.formatMask function.
  • Added math widget in v2.16.0-beta
  • This widget will only work in tablesorter version 2.16+ and jQuery version 1.7+.
  • It adds basic math capabilities. A full list of default formulas is listed in the "Attribute Settings" section.
  • Add your own custom formulas which manipulating an array of values gathered from the table by row, column or a column block (above).
  • This is by no means a comprehensive widget that performs like a spreadsheet, but you can customize the data gathering "type" and available "formula", as desired.
  • The widget will update the calculations based on filtered rows, and will update if any data within the table changes (using update events).
  • This widget is not optimized for very large tables, for two reasons:
    • On initialization, it cycles through every table row, calculates the column index , and adds a data-column attribute (Fixed in v2.25.0).
    • It uses the update method whenever it recalculates values to make the results sortable. This occurs when any of the update methods are used and after the table is filtered.
  • When setting tablesorter's debug option to true, this widget will output each {type}-{formula} value found, the array of numbers used and the result.

Options

Math widget default options (added inside of tablesorter widgetOptions)

TIP! Click on the link in the option column to reveal full details (or toggle|show|hide all) or double click to update the browser location.
OptionDefaultDescription
math_data 'math' Set this option to point to the named data-attribute. For example, when set to 'math', the widget looks for settings within the data-math attribute.
math_debug false Set this option to true to enable the debug log of the math widget without all the extra noise from the overall debug option (v2.27.0).
'' Cell attribute (data-attribute) containing the math value to use. This defaults to the textAttribute value when the textExtraction option is set to "basic" (v2.31.1).

Use this option as follows:
// Include the "data-" prefix in the option
math_textAttr : 'data-math-value'
<td data-math-value="1000">1.0k</td>
'recalculate' Set this option change the name of the event that the widget listens for to perform an update.

By default, recalculations are performed after:

  • Tablesorter initialization.
  • After any call to a tablesorter method which updates the internal cache (e.g. "update", "updateCell", etc). The math widget listens for the updateComplete event, which occurs after the internal cache has completed updating, before recalculating values.
  • After a "filterReset".
  • And after a "filterEnd" event, or a "pagerComplete" event (if the pager is being used), but not both!
[ ] Set this option the column index of columns of data to ignore.

To ignore the first and second columns in a table, set this option using zero-based column indexs as follows:
// column index(es) to ignore
math_ignore : [0,1]
'N/A' This option contains the text added to a math cell when no matching elements are found (v2.24.0; v2.25.0).

In v2.25.0, this option can now be set to an empty string.

To understand when this text is used, select a Region in the "Row & Column Sums" table below. The totals for hidden rows will display this text.

Use it as follows:

math_none : 'N/A',
math_complete : function($cell, wo, result, value, arry) {
  // don't include currency symbol when no result is available
  return value === wo.math_none ? value : '$ ' + value;
}
'#,##0.00' Set this option with an output formatting mask to use

As of v2.16.2, you can set a mask for each math cell by adding a data-math-mask data-attribute (the math part of the data-attribute is named from the math_data setting).

<th data-math="all-sum" data-math-mask="##0.00">all-sum</th>

Javascript-number-formatter details

Features

  • Short, fast, flexible yet standalone. Only 75 lines including MIT license info, blank lines & comments.
  • Accept standard number formatting like #,##0.00 or with negation -000.####.
  • Accept any country format like # ##0,00, #,###.##, #'###.## or any type of non-numbering symbol.
  • Accept any numbers of digit grouping. #,##,#0.000 or #,###0.## are all valid.
  • Accept any redundant/fool-proof formatting. ##,###,##.# or 0#,#00#.###0# are all OK.
  • Auto number rounding.
  • Include a prefix & suffix with the mask
  • Simple interface, just supply mask & value like this: $.tablesorter.formatMask( "0.0000", 3.141592, "prefix ", " suffix" );
    $.tablesorter.formatMask( "$ 0.0000 USD", 1234.567, "prefix ", " suffix" );
    // prefix $ 1234.5670 USD suffix

Limitation

  • No scientific/engineering formatting.
  • Not for date or phone formation.
  • No color control.
  • No prefix or suffix is allowed except leading negation symbol. So $#,##0.00 or #,###.##USD will not yield expected outcome. Use '$'+ $.tablesorter.formatMask('#,##0.00', 123.45) or $.tablesorter.formatMask('#,##0.00', 456.789) + 'USD'
  • The prefix or suffix can not include any numbers (0-9), hashes (#), dashes (-), or plus signs (+)

Note

  • The difference between using # and 0 in the mask, is that when a value of zero is passed to the function, the # mask will return an empty string whereas the 0 mask will return a zero.
  • When there's only one symbol is supplied, system will always treat the single symbol as Decimal. For instance, $.tablesorter.formatMask( '#,###', 1234567.890) will output 1234567,890.
  • To force a single symbol as Separator, add a trailing dot to the end like this: $.tablesorter.formatMask( '#,###.', 1234567.890) which will then output 1,234,567.
  • Original plugin demo
The number formatter code was copied from javascript-number-formatter (MIT) - now forked on GitHub (updated demo).
null This function is called after each calculation is made to allow re-formatting, adding prefixes, suffixes, etc to the result.

Use this option as follows:
// complete executed after each function
math_complete : function($cell, wo, result, value, arry) {
    return '$ ' + result + $cell.attr('data-suffix');
}
  • $cell - the target cell (jQuery object)
  • wo - tablesorter's widget options (from table.config.widgetOptions).
  • result - the formatted result of the calculation.
  • value - an unformatted result of the calculation.
  • arry - the array of values gathered by the widget.
In this function, if a anything is returned, it will be automatically added to the $cell as html. Or, return false and no change is made to the cell contents; use this method if you manipulate the $cell contents and don't want the widget to do it.

If you need to format the data output after manipulating the value, you can use wo.math_mask, or a different mask, by using the $.tablesorter.formatMask( mask, value ); function. For example:
math_complete : function($cell, wo, result, value, arry) {
    var percent = Math.round( value * 1e4 ) / 100; // percent with two decimal places
    return $.tablesorter.formatMask( wo.math_mask, percent ) + ' %';
}
More details can be found in the math_mask description.
null This function is called after all math recalculations have completed.

Use this option as follows:
// complete executed after each function
math_completed : function(config) {
    var total = config.$table.find('[data-math="all-sum"]:last').text();
    console.log(total);
}
[ 'row', 'above', 'below', 'col' ] This is the order of calculations (v2.24.0).
  • By default, the widget cycles through the calculated cells as follows:
    • Search all non-informational tbodies for data-math table cells (data-attribute set by math_data option).
    • Cycle through these cells by priority: row, above, col (set by this option).
    • Search all informational tbodies, and tfoot for data-math table cells.
    • Cycle through these cells by priority: row, above, col (set by this option).
    • Search the entire table for data-math cells of the "all" type.
  • So, all row calculations are made first, followed by "above" calculations then "col" (column) calculations.
  • The "all" type calculations are always performed last, and therefore the type is not included in this list.
  • Change this order if the order of calculations needs to be made column first, followed by rows.
  • For more details about the differences between "col" and "above" types, see the "Attribute Settings" section.
'' Add content before the value formatted by the math_mask option (v2.16.4).
  • This option adds content before the mask.
  • If the mask includes any content for the prefix, then this value is added before it.
  • If this option contains a {content} tag, the prefix within the mask will replace this tag.
    math_mask   : '$ #,##0.00',
    math_prefix : '{content}'
    
    // result of the value 12345.67
    // <span class="blue">$ </span>12,345.67
    You can experiment with this option in the "Mask Examples" section.
'' Add content after the value formatted by the math_mask option (v2.16.4).
  • This option adds content after the mask.
  • If the mask includes any content for the suffix, then this value is added after it.
  • If this option contains a {content} tag, the suffix within the mask will replace this tag.
    math_mask   : '#,##0.00 USD',
    math_suffix : '{content}!'
    
    // result of the value 12345.67
    // 12,345.67 USD<span class="red">!</span>
    You can experiment with this option in the "Mask Examples" section.
'' Set this option apply a filter to targeted rows (v2.24.6; v2.25.0).

This option applys the set filter (jQuery .filter() to the targeted rows.

If this option is set, rows filtered out by the filter widget are included, so you will need to include them in this selector if you wish to filter them out (e.g. ':visible:not(.filtered)' (only include visible & rows not filtered out by the filter widget)

// this option will accept any of the jQuery filter types (i.e. selector, function or elements)
// for example, here is the functional equivalent
// math_rowFilter : function(index, element) { return $(element).is(':visible:not(.filtered)'); }
math_rowFilter : ':visible:not(.filtered)'
In v2.25.0, this setting may be overridden for each math type by adding a data-math-filter attribute (The "math" portion is set by the math_data option) to the cell.
<td data-math-filter=":visible" data-math="all-sum">...</td>
Note The data-math-filter attribute is ignored if set to an empty string; instead use data-math-filter="*" to target all rows as done in the first example on this page.

Methods

Recalculate

Recalculate the values of all math cells within the table using the following method:
$('table').trigger('recalculate');

The triggered 'recalculate' method can be renamed by modifying the math_event option.

This method is automatically called:
  • Tablesorter initialization.
  • After any call to a tablesorter method which updates the internal cache (e.g. "update", "updateCell", etc). The math widget listens for the updateComplete event, which occurs after the internal cache has completed updating, before recalculating values.
  • After a "filterReset".
  • And after a "filterEnd" event, or a "pagerComplete" event (if the pager is being used), but not both!

Attribute Settings

The math widget data-attibute setting requires two parts: type & formula
<td data-math="{type}-{formula}"></td>
When set, the data is gathered based on the math type ("row", "column", "above", "below" or "all") and passed to the formula as an array.

{type} (data gathering)

  • row - gather the table cell values from the same row as the data-math attribute.
  • above - gather the table cell values from the same column as the data-math attribute, but stop when the first table cell is reached, or when another cell with a data-attribute with an "above" type is reached; see the first table demo below to see why this is useful.
  • below (v2.24.0) - gather the table cell values from the same column as the data-math attribute, but stop when the last table cell is reached, or when another cell with a data-attribute with a "below" type is reached.
  • col - gather the table cell values from the same column as the data-math attribute.
  • all - gather all table cell values with a data-math attribute that start with "all".

{formula} (defaults)

  • count - returns the count (length) of the data set.
  • sum - returns the sum of all values in the data set.
  • max - returns the maximum value in the data set.
  • min - returns the minimum values in the data set.
  • mean - returns the mean (average) of all values in the data set; it uses the sum formula in part of the calculation.
  • median - returns the median (middle value) of the data set.
  • mode - returns an array of the mode(s) (most frequent value or values) in the data set; an array is always returned, even if only one mode exists (see the second demo below).
  • range - returns the range (highest minus lowest value) of the data set.
  • varp - returns the variance of the data set (population).
  • vars - returns the variance of the data set (sample).
  • stdevp - returns the standard deviation of the data set (population).
  • stdevs - returns the standard deviation of the data set (sample).
  • custom (not a default)
    • Custom formulas can have any name
    • Return your result after making whatever calculation from the array of data passed to the formula
    • For example:
      // adding a custom equation... named "product"
      // access from data-math="row-product" (or "above-product", "below-product" or "col-product")
      // config parameter added v2.24.0 to allow access to table settings
      $.tablesorter.equations['product'] = function(arry, config) {
          // multiple all array values together
          var product = 1;
          $.each(arry, function(i,v) {
              // oops, we shouldn't have any zero values in the array
              if (v !== 0) {
                  product *= v;
              }
          });
          return product;
      };

Ignoring cells

  • Entire row: if the <tr> math data-attribute contains the keyword "ignore" then that entire row of cells will be skipped when building the array of data to be used for calculations.
    <tr data-math="ignore"><td>1</td><td>2</td><td>3</td></tr>
  • Cell: if the table cell math data-attribute contains the keyword "ignore" then that cell will be skipped when building the array of data to be used for calculations.
    <td data-math="ignore">1</td>
  • Column: set the widget math_ignore option with an array of zero-based column indexes of columns to ignore or skip when building the array of data for calculations.
    math_ignore : [0,1]

Targeting cell content

  • Version 2.27.0 added a new data-attribute. The data-math-target attribute value must contain an element selector within the same cell.
    <tr>
      <td data-math="sum-above" data-math-target=".sum">The total value is <span class="sum"></span></td>
    </tr>
  • If you're using the grouping widget and want to sum up the value of the group, you'll need to also include a data-column attribute to target the table column to sum. Here is a JSFiddle demonstrating how to combine the two widgets.
    <tr>
      <td colspan="5" data-math="sum-above" data-math-target=".sum" data-column="3">The total value is <span class="sum"></span></td>
    </tr>

Mask Examples

The formatting function can be used separately from the math widget:
// $.tablesorter.formatMask(mask, value, prefix, suffix);
$.tablesorter.formatMask('$#,##0.00 USD', 12345.678, 'prefix ', ' suffix');
// result: "prefix $12,345.68 USD suffix"
  • The $.tablesorter.formatMask function has the following parameters:
    • mask - please refer to the math_mask option for more details.
    • value - number to be formatted.
    • prefix - please refer to the math_prefix option for more details (v2.16.4).
    • suffix - please refer to the math_suffix option for more details (v2.16.4).

Note The difference between using # and 0 in the mask, is that when a value of zero is passed to the function, the # mask will return an empty string whereas the 0 mask will return a zero.

$.tablesorter.formatMask('$#,##0.00 USD', 0); // result: "$0.00 USD"
$.tablesorter.formatMask('$#,###.00 USD', 0); // result: "$.00 USD"
$.tablesorter.formatMask('$#,###.#0 USD', 0); // result: "$.00 USD"
$.tablesorter.formatMask('$#,###.## USD', 0); // result: "$ USD"

Experiment with the mask:


		
Value to use:
Prefix: ( add {content} to include the mask prefix )
Suffix: ( add {content} to include the mask suffix )

Demo

Row & Column Sums

Region Salesman FastCar RapidZoo SuperGlue Grand Total
Column Totals col-sum col-sum col-sum col-sum
Visible Total
Grand Total
MiddleJoseph$ 423$ 182$ 255row-sum
MiddleLawrence$ 5,908$ 4,642$ 4,593row-sum
MiddleMaria$ 6,502$ 3,969$ 5,408row-sum
MiddleMatt$ 4,170$ 6,093$ 5,039row-sum
Middle Total above-sum above-sum above-sum above-sum
NorthJoseph$ 3,643$ 5,846$ 6,574row-sum
NorthLawrence$ 4,456$ 6,658$ 7,685row-sum
NorthMaria$ 6,235$ 4,616.99$ 3,612.33row-sum
NorthMatt$ 3,868$ 3,926$ 3,254row-sum
North Total above-sum above-sum above-sum above-sum
WestJoseph$ 5,507$ 5,186$ 4,882row-sum
WestLawrence$ 4,082$ 5,272$ 6,124row-sum
WestMaria$ 5,520$ 5,461$ 4,872row-sum
WestMatt$ 6,737$ 4,598$ 4,233row-sum
West Total above-sum above-sum above-sum above-sum

Math Formulas

FormulaABCDEFResult (expected result)
Default Formulas
Count (row-count)101010102020
Sum (row-sum)102010103020
Max (row-max)20603015305
Min (row-min)20603015305
Mean (row-mean)102030103020
Median (row-median)1053443
Mode (row-mode)122232
Mode (row-mode)122134
Range (row-range)1-22460
Variance [population] (row-varp)274554
Standard Deviation [population] (row-stdevp)274554
Variance [sample] (row-vars)274554
Standard Deviation [sample] (row-stdevs)274554
Custom Formulas
Custom ( (A+B+C)*D - (E/F)*100 )5232012
Product ( A*B*C*D*E*F )1234510

Page Header

<!-- load your chosen theme -->
<link rel="stylesheet" href="css/theme.blue.css">

<!-- jQuery -->
<script src="js/jquery.min.js"></script>

<!-- Tablesorter: required -->
<script src="js/jquery.tablesorter.js"></script>
<script src="js/widget-math.js"></script>

<!-- load filter widget if needed -->
<script src="js/widget-filter.js"></script>

Javascript


	

CSS


	

HTML