简体   繁体   中英

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: 在此处输入图像描述

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM