rshinynumeric-input

R Shiny numeric input automatically format as decimal, possibly using shinyWidgets::autonumericinput()


I have several numeric input boxes in a shiny app for the user to enter lat/long values. I am wondering if it's possible to format it so the user doesn't have to type in the decimal or the minus sign in the longitude box.

For example, in Access (I'm converting an access form into a shiny app), the entry box looks like this: enter image description here

I know I can use regular expressions to do it behind the scenes, but I'm hoping to do it before the user's eyes. Currently, I just have a standard numericInput('Latitude', Latitude, value = NA). I found autonumericInput() in the shinyWidgets library, which seems promising, but I'm not sure how to wrangle it.


Solution

  • We can use updateNumericInput with some stringr functions. For example, to set a decimal place after two digits:

    library(shiny)
    library(stringr)
    
    ui <- fluidPage(
      numericInput("lat", "Insert Latitude", "")
    )
    
    server <- function(input, output, session) {
      observeEvent(input$lat, {
        if (!is.na(input$lat)) {
          if (str_length(input$lat) > 2 & !str_detect(input$lat, "\\.")) {
            x <- input$lat
            str_sub(x, 3) <- str_c(".", str_sub(x, 3))
            updateNumericInput(session, inputId = "lat", value = as.numeric(x))
          }
        }
      })
    }
    
    shinyApp(ui, server)