How to format a number with specified level of precision?

format, r

Solution

You can use the signif function to round to a given number of significant digits. If you don't want extra trailing 0's then don't "print" the results but do something else with them.

> somenumbers <- c(0.000001234567, 1234567.89) 
> options(scipen=5)
> cat(signif(somenumbers,3),'\n')
0.00000123 1230000 
> 

Problem

I would like to create a function that returns a vector of numbers a precision reflected by having only n significant figures, but without trailing zeros, and not in scientific notation e.g, I would like ``` somenumbers <- c(0.000001234567, 1234567.89) myformat(x = somenumbers, n = 3) ``` to return ``` [1] 0.00000123 1230000 ``` I have been playing with `format`, `formatC`, and `sprintf`, but they don't seem to want to work on each number independently, and they return the numbers as character strings (in quotes). This is the closest that i have gotten example: ``` > format(signif(somenumbers,4), scientific=FALSE) [1] " 0.000001235" "1235000.000000000" ```

Original source