12

I just trying to round in R number like:

> round(1.327076e-09)

I would like it to result in

> 1.33e-09

but results in

> 0

which function can use?

Obromios
  • 15,408
  • 15
  • 72
  • 127
stefan
  • 171
  • 2
  • 6
  • 2
    Why should it return `1.32e-09` shouldn't it be `1.33e-09`? Or do you want to just truncate the number after the second dp? – Gavin Simpson Apr 15 '11 at 11:09

3 Answers3

20

Try signif:

enter image description here

> signif(1.326135235e-09, digits = 3)
[1] 1.33e-09
Tapper
  • 1,393
  • 17
  • 28
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
8

Use signif:

x <- 1.327076e-09 
signif(x,3)
[1] 1.33e-09

or sprintf:

sprintf("%.2e",x)
[1] "1.33e-09"
James
  • 65,548
  • 14
  • 155
  • 193
  • 4
    Good call with `sprintf`. In general, you only want to lose precision when displaying numbers, not in the actual calculations. `round` and `signif` should be used sparingly. – Richie Cotton Apr 15 '11 at 13:01
2

The function round will do rounding and you can specify the number of decimals:

x <- 1.327076e-09
round(x, 11)
[1] 1.33e-09

Rising to the challenge set by @Joris and @GavinSimpson - to use trunc on this problem, do the following:

library(plyr)
round_any(x, 1e-11, floor)
[1] 1.32e-09
Andrie
  • 176,377
  • 47
  • 447
  • 496