How to round a number and show it zeros?

The general code in R for rounding a number is to say 2 decimal points:

> a = 14.1234 > round(a, digits=2) > a > 14.12 

However, if a number has zeros as the first two decimal digits, R suppresses zeros on the display:

 > a = 14.0034 > round(a, digits=2) > a > 14 

How can we do R to show the first decimal digits, even if they are zeros? I especially need this in the plots. I searched here and some people suggested using options(digits=2) , but that makes R have weird behavior.

+6
source share
3 answers

We can use format

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

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

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

data

 a <- 14.0034 
+9
source

Try the following:

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

What about:

 a=14.0034 formatC(a,2,format="f") #[1] "14.00" 
0
source

Source: https://habr.com/ru/post/1014787/


All Articles