Search code examples
rshinyrhandsontable

How to dynamically set number of decimal places using rhandsontable?


In the below MWE code I'm trying to have a user input (deciInputs) set the number of decimal places rendered in the rhandsontable table. As the code is drafted, strangely, a user input of 0 renders 1 decimal place in the table, setting the user input to 1 renders 0 decimal places, and setting the user input to any value > 1 (let's call this user input value "x") results in rendered decimal places of x - 1 (where, for example setting x = 3 results in 2 rendered decimal places). Try it out, you'll see. Further, for example if the user input is set to 1, I'd like a user input of 12 directly into the table itself (overriding the default value) to be rendered as 12.0, a user input of 12.1 rendered as 12.1, a user input of 12.12 rendered as 12.1, a user input of 12.129 rendered as 12.1, etc. and this doesn't work quite right either. What am I doing wrong in the below code?

Code:

library(shiny)
library(rhandsontable)

ui <- fluidPage(
    sliderInput("deciInputs","Decimal places:",min = 0,max = 6,value = 2),
    rHandsontableOutput("data_table")
)

server <- function(input, output) {
  data <- reactive({
    df <- data.frame(data_set = c(3.14159, 2.71828, 1.61803))
  })
  
  output$data_table <- renderRHandsontable({
    df <- data()
    rh <- rhandsontable(df, readOnly = FALSE)
    for (col in 1:ncol(df)) {
        rh <- hot_col(rh, col, format = sprintf("0.%df", input$deciInputs))
        }
    return(rh)
  })
}

shinyApp(ui, server)

Solution

  • Try with format = format(0, nsmall = input$deciInputs):

    sprintf("0.%df", 4)
    #> [1] "0.4f"
    format(0, nsmall = 4)
    #> [1] "0.0000"
    

    Created on 2024-04-23 with reprex v2.1.0

    library(shiny)
    library(rhandsontable)
    
    ui <- fluidPage(
      sliderInput("deciInputs","Decimal places:",min = 0,max = 6,value = 2),
      rHandsontableOutput("data_table")
    )
    
    server <- function(input, output) {
      data <- reactive({
        df <- data.frame(data_set = c(3.14159, 2.71828, 1.61803))
      })
      
      output$data_table <- renderRHandsontable({
        df <- data()
        rh <- rhandsontable(df, readOnly = FALSE)
        for (col in 1:ncol(df)) {
          rh <- hot_col(rh, col, format = format(0, nsmall = input$deciInputs))
        }
        return(rh)
      })
    }
    
    shinyApp(ui, server)
    #> 
    #> Listening on http://127.0.0.1:4368
    

    Created on 2024-04-23 with reprex v2.1.0