Home > Enterprise >  How to count number of characters in a decimal (including . and trailing zeros) using R
How to count number of characters in a decimal (including . and trailing zeros) using R

Time:07-15

Good day all,

I am trying to count the number of characters in a decimal with trailing zeros when my micrometer sent its numeric input to my shiny app. My count should include both the . and any trailing zeros.

Example: 0.500 should have a total of 5 characters and 0.600000 should have 8.

Initially, I tried converting it to character:

nchar(as.character(0.500))
[1] 3
as.character(0.500)
[1] "0.5"

Then I tried using paste0 but it won't retain the trailing zeros

paste0("'",0.500,"'")
[1] "'0.5'"

Here is a reproducible example of a shiny app that works similarly to my existing application:

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
   dashboardHeader(
     title = "Test"
   ),
      dashboardSidebar(collapsed = T),
      dashboardBody(
         fluidRow(
            column(width = 4,
         numericInput(inputId = "data_input",
                      label = "Data",
                      value = 0.500
                      )
  ),
  
  column(width = 8,
         textOutput("data_output")
     )
   )
  )
)

server <- function (input, output, session) {

  output$data_output <- renderPrint("Does not have 5 characters!")

  observe({
    if(nchar(input$data_input) > 4){
     output$data_output <- renderPrint({
    "Yah! 5 characters now!"
   })
     } else {
       output$data_output <- renderPrint("Does not have 5 characters!")
     }
    })
}
shinyApp(ui, server)

I have tried looking for a solution for the past 2 hours but I can't seem to locate any. Thanks for your help!

CodePudding user response:

You can probably combine the solution provided here by adding the nchar(0.5) to the number of trailing zero's:

enter image description here

  • Related