Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not display decimal point in sprintf for integers

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))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"   
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading