Joe
Joe

Reputation: 1768

How to display numbers in renderTable with the correct number of decimal places?

In my shiny app I have a renderTable filled with whole numbers as well as decimal numbers. My goal is to display the whole numbers without any decimal place, i. e. 1 should be displayed as "1", and the decimal numbers with all decimal places, i. e. 1.2345 should be displayed as "1.2345". I should mention that the numbers stem from user input. Thus, I do not know in advance how many decimal places they will have. Please see the following example:

library(shiny)

ui <- fluidPage(
  numericInput("number", "enter a number", value = 1.2345),
  tableOutput("table"))

server <- function(input, output, session) {
  output$table <- renderTable({data.frame(c(1, input$number))}, digits = 0)}

shinyApp(ui, server)

As you can see I am aware of the digits argument of renderTable, but I do not see how to make use of it in my case.

Upvotes: 4

Views: 3805

Answers (1)

lukeA
lukeA

Reputation: 54237

Wrap the output in as.character:

server <- function(input, output, session) {
  output$table <- renderTable({
    data.frame(as.character(c(1, input$number)))
  }, rownames = T)
}

Upvotes: 4

Related Questions