Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force R to always round up to two decimal places

Tags:

rounding

r

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.

like image 245
Max H. Avatar asked Nov 27 '25 04:11

Max H.


1 Answers

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.

like image 137
Valkyr Avatar answered Nov 29 '25 18:11

Valkyr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!