Christian
Christian

Reputation: 477

How to display values in a "numericInput" in shiny as percentage?

I have created a shiny web-page and in the sidebarPanel I use several numericInput-fields. Some of them should display values as percentage and it should not be a slider. Does someone have an idea how to format the numericInput-fields?

Upvotes: 10

Views: 2867

Answers (2)

Adriana Huante
Adriana Huante

Reputation: 362

You can use shinyWidgets::currencyinput with format = "percentageUS2dec" like this

currencyInput("perc", "Example", value = 0.3, format = "percentageUS2dec"),

Resulting in the following input enter image description here

Upvotes: 1

Jan
Jan

Reputation: 5264

I can think of two ways of doing that.

1. Formatted Content

Use a text field in the and parse the content in the server code. The solution can only handle integers at this point. Basically, it works. However, interacting with it does not always give you the best usability.

ui <- fluidPage(
    titlePanel("Parsed Input with Unit Example"),
    textInput("inpPercent", "Chances of Success", value = "20 %"),
    h1(textOutput("txtSuccess"))
)
server <- function(session, input, output) {
  observeEvent( input$inpPercent,{
    Format <- "^[-+]?[ ]*[0-9]*[ ]*[%]?$"

    # Trim
    inp <- gsub("^\\s+|\\s+$", "", input$inpPercent)
    
    if (!grepl(Format, inp)) {
      Result <- "Invalid format"
      inp <- numeric()
    } else {
      # Remove all spaces
      inp <- gsub("[[:space:]]", "", inp)
      # Split
      if (grepl("%", inp)) inp <- gsub("%", "", inp)
      inp <- suppressWarnings( as.numeric(inp) )
      if (is.na(inp)) {
        Result <- "Invalid format2"
        inp <- numeric()
      } else {
        Result <- paste("Percent:", inp)
      }
    }
  
    print(Result)
    output$txtSuccess <- renderPrint(Result)
    if (length(inp) > 0)
      updateTextInput(session, inputId = "inpPercent", value = paste(inp, "%"))
  })
}

2. Shiny Widgets: numericInputIcon

Use the widget numericInputIcon from the shinyWigdets package. It is very easy to set up a widget like that. The documentation provides an example for percentages, too.

Example of a numericInputIcon widget

Upvotes: 2

Related Questions