diff --git a/R/format.R b/R/format.R index c77529fb..c35c5354 100644 --- a/R/format.R +++ b/R/format.R @@ -44,6 +44,9 @@ formatColumns = function(table, columns, template, ...) { #' # render vapor pressure with only two significant figures. #' datatable(pressure) %>% formatSignif('pressure',2) #' +#' # render vapor pressure with only two 2-decimal digits in exponential format. +#' datatable(pressure) %>% formatExp('pressure',2) +#' #' # apply CSS styles to columns #' datatable(iris) %>% #' formatStyle('Sepal.Length', fontWeight = styleInterval(5, c('bold', 'weight'))) %>% @@ -93,6 +96,15 @@ formatSignif = function( formatColumns(table, columns, tplSignif, digits, interval, mark, dec.mark) } + +#' @export +#' @rdname formatCurrency +formatExp = function( + table, columns, digits = 2, interval = 3, mark = ',', dec.mark = getOption('OutDec') +) { + formatColumns(table, columns, tplExp, digits, interval, mark, dec.mark) +} + #' @export #' @rdname formatCurrency #' @param method the method(s) to convert a date to string in JavaScript; see @@ -210,6 +222,12 @@ tplSignif = function(cols, digits, interval, mark, dec.mark, ...) { ) } +tplExp = function(cols, digits, interval, mark, dec.mark, ...) { + sprintf( + "DTWidget.formatExp(this, row, data, %d, %d, %d, '%s', '%s');", + cols, digits, interval, mark, dec.mark + ) +} tplDate = function(cols, method, params, ...) { params = if (length(params) > 0) paste(',', toJSON(params)) else '' sprintf("DTWidget.formatDate(this, row, data, %d, '%s'%s);", cols, method, params) diff --git a/inst/htmlwidgets/datatables.js b/inst/htmlwidgets/datatables.js index a097c68c..7faed17e 100644 --- a/inst/htmlwidgets/datatables.js +++ b/inst/htmlwidgets/datatables.js @@ -8,8 +8,9 @@ var DTWidget = {}; // 123456666.7890 -> 123,456,666.7890 -var markInterval = function(d, digits, interval, mark, decMark, precision) { +var markInterval = function(d, digits, interval, mark, decMark, precision, exponential) { x = precision ? d.toPrecision(digits) : d.toFixed(digits); + if(exponential) {x = exponential ? d.toExponential(digits) : d.toFixed(digits);}; if (!/^-?[\d.]+$/.test(x)) return x; var xv = x.split('.'); if (xv.length > 2) return x; // should have at most one decimal point @@ -53,6 +54,13 @@ DTWidget.formatSignif = function(thiz, row, data, col, digits, interval, mark, d .html(markInterval(d, digits, interval, mark, decMark, true)); }; +DTWidget.formatExp = function(thiz, row, data, col, digits, interval, mark, decMark) { + var d = parseFloat(data[col]); + if (isNaN(d)) return; + $(thiz.api().cell(row, col).node()) + .html(markInterval(d, digits, interval, mark, decMark, false,true)); +}; + DTWidget.formatDate = function(thiz, row, data, col, method, params) { var d = data[col]; if (d === null) return;