How to round a number and make it show zeros?

The formatC function works nicely if you apply it to the vector after rounding. Here the inner function round rounds to two decimal places then the outer function formatC formats to the same number of decimal places as the number were rounded to. This essentially re-adds zeros to the number that would otherwise end without the decimal places (e.g., 14.0034 is rounded to 14, which becomes 14.00).

a=c(14.0034, 14.0056) 
formatC(round(a,2),2,format="f")
#[1] "14.00", "14.01"

We can use format

format(round(a), nsmall = 2)
#[1] "14.00"

As @arvi1000 mentioned in the comments, we may need to specify the digits in round

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

data

a <- 14.0034

Try this:

a = 14.0034 
sprintf('%.2f',a) # 2 digits after decimal
# [1] "14.00"

Tags:

R