Home > Mobile >  Not display decimal point in sprintf for integers
Not display decimal point in sprintf for integers

Time:03-16

I need to convert some numeric values to characters in R. I want to show trailing zeros if relevant, and no decimal place if the nuumber is an integer. For example, in the code below, I need my output to be "11" "0.30" "0.00050" "3.1" "4.6". How do I get the 11 to display as "11" not "11."

sprintf('%#.2g', c(11, 0.301, 0.000502, 3.12, 4.56))

CodePudding user response:

You can remove the trailing . like this:

sprintf('%#.2g', c(11, 0.301, 0.000502, 3.12, 4.56)) |> stringr::str_remove("[.]$")
#> [1] "11"      "0.30"    "0.00050" "3.1"     "4.6"   
  • Related