Question

I would like to convert a number to a specified number of significant figures, e.g. some function that returns "1.0" (as a character) from FUN(1.01). (I need a character because the value will be used in an xtable.

I suspect that this is trivial, but I am having trouble.

Here is what I have tried:

> signif(1.01, 2)
[1] 1
> round(1.01, 2)
[1] 1.01
> format(1.01, digits = 2)
[1] "1"
> as.character(trunc(1.20, 3))
[1] "1"
> as.character(round(1.01, digits = 2))
[1] "1"

Is there a function that will do this?

Was it helpful?

Solution

Try ?sprintf:

> sprintf("%0.1f", 1.01)
[1] "1.0"

There's also format and formatC, which you may find more user-friendly:

> format(1.01,digits=1,nsmall=1)
[1] "1.0"
> formatC(1.01,digits=1,format="f")
[1] "1.0"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top