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

Force R to always round up to two decimal places

I am looking for a solution but could not find a solution yet.
Really basic, i want R to always round up my numbers until two decimal places so

2,3421 should be rounded to 2,35

a <- 2.3423
format(round(a,digits=2),nsmall=2)

still gives
2.34
I am new to R and related topics always seemed to be a little different.
Thanks for any help.

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 :

If your numbers are in a numeric vector :

format(round(a,digits=2),nsmall=2)

which gives a character vector. The format function is there so that 1 is displayed as 1.00 and not 1 for example. If you don’t care about that, omit it.


If you want 2.3421 to be rounded to 2.35 (not standard rounding but ceiling at 2 decimals), use

format(ceiling(a*100)/100,nsmall=2)

or more legible with pipes:

a %>% multiply_by(100) %>% ceiling %>% divide_by(100) %>% format(2)

Without format: ceiling(a*100)/100 which gives you a numeric.

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