[R] number of decimal places in a number?
Petr Savicky
savicky at cs.cas.cz
Sun Jul 8 21:47:22 CEST 2012
On Sat, Jul 07, 2012 at 11:52:35AM +0300, Martin Ivanov wrote:
> Dear R users,
>
> I need a function that gets a number and returns its number of actual decimal places.
> For example f(3.14) should return 2, f(3.142) should return 3, f(3.1400) should also return 2
> and so on. Is such function already available in R? If not, could you give me a hint how to achieve that?
Hi.
Try the following.
getDigits <- function(x)
{
out <- format.info(x, digits=10)
stopifnot(out[3] == 0)
out[2]
}
The function format.info() rounds the input number
to "digits" significant digits and then outputs the
width of the field for printing, the number of digits
after the decimal dot and some information on the exponent
(out[3] == 0, if exponent is not used). So, the required
number of digits in the fractional part is out[2].
getDigits(3.123456)
[1] 6
Hope this helps.
Petr Savicky.
More information about the R-help
mailing list