Home > other >  Force R to always round up to two decimal places
Force R to always round up to two decimal places

Time:04-07

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.

CodePudding user response:

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.

  • Related