user1701545
user1701545

Reputation: 6190

Rounding small floating point numbers

Suppose I have a numeric vector which I'd like to round to 'prettier' numbers, such as:

vec <- c(1.739362e-08,8.782537e-08,0.5339712)

I'd like it to be:

pretty.vec <- c(1.74e-08,8.78e-08,0.53)

How do I achieve that? using round doesn't really help since it rounds the first two elements to 0:

> round(vec,2)
[1] 0.00 0.00 0.53

Upvotes: 2

Views: 108

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226027

How about ?signif ? (Depending on your application you could also use print(...,digits=3))

vec <- c(1.739362e-08,8.782537e-08,0.5339712)
signif(vec,digits=3)
## [1] 1.74e-08 8.78e-08 5.34e-01
print(vec,digits=3)
## [1] 1.74e-08 8.78e-08 5.34e-01

It's fairly hard to get R to format the elements of a vector differently from each other: usually it assumes you want that consistency.

print(sprintf("%1.3g",vec),quote=FALSE)
## [1] 1.74e-08 8.78e-08 0.534   

Also related: ?format, ?options (see "scipen")

Upvotes: 5

Related Questions