Format number into K(thousand), M(million) in Shiny DataTables

跟風遠走 提交于 2021-01-05 07:47:04

问题


I'm looking for a straight forward way to change the formatting of numbers into K,M in shiny dataTables. Preferably with something like formatCurrency. I don't want to write k, m functions to convert number into string in order to do the formatting as it makes it difficult to sort rows by value.


回答1:


There's no built-in way to do this, but it's not too bad to write your own format function in JavaScript that doesn't break row sorting.

See Column Rendering in the DT docs for how to do this: https://rstudio.github.io/DT/options.html

And this will also help: https://datatables.net/reference/option/columns.render

Here's an example of a custom thousands formatter that rounds to 1 decimal place:

library(DT)

formatThousands <- JS(
  "function(data) {",
  "return (data / 1000).toFixed(1) + 'K'",
  "}")

datatable(datasets::rock, rownames = FALSE, options = list(
  columnDefs = list(list(
    targets = 0:1, render = formatThousands
  ))
))


来源:https://stackoverflow.com/questions/46656851/format-number-into-kthousand-mmillion-in-shiny-datatables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!