[R] round number

Petr Savicky savicky at praha1.ff.cuni.cz
Sat Mar 26 21:42:59 CET 2011


On Sat, Mar 26, 2011 at 07:05:40PM +0100, Alfredo Alessandrini wrote:
> Hi,
> 
> > a <- 4
> 
> > a*0.2
> [1] 0.8
> 
> ok!!
> 
> Is there a method to obtain this:
> 
> > a*0.2
> [1] 0.80
> 
> I need to round the number also with the zero.

Hi.

Try the following

  formatC(a*0.2, digits=2, format="f")
  [1] "0.80"

  noquote(formatC(a*0.2, digits=2, format="f"))
  [1] 0.80

The two-digit form 0.80 is used also if a vector is printed
and some other component requires 2 digits. For example

  c(a*0.2, 0.01)
  [1] 0.80 0.01

Hope this helps.

Petr Savicky.



More information about the R-help mailing list