[R] as.numeric looses precision

Sarah Goslee sarah.goslee at gmail.com
Thu Jul 2 16:27:06 CEST 2015


Hi Roger,

You're mixing up storage and display:

p <- "1087.003489"
p <- as.numeric(p)

> p
[1] 1087.003 # the default value for digits = 7, which can be changed
with option()
> print(p, digits=4)
[1] 1087
> print(p, digits=10)
[1] 1087.003489

But note also:

> print(p, digits=20)
[1] 1087.003488999999945
(And see FAQ 7.31 if you don't understand why.)

Sarah

On Thu, Jul 2, 2015 at 9:54 AM, Bos, Roger <roger.bos at rothschild.com> wrote:
> I have a string that contains a number and when I convert it to a number I loose precision and I would like to know if there is a way to avoid that.  Here is my example:
>
> p <- "1087.003489"
> as.numeric(p, digits=6)
>
> R gives me 1087.003:
>
>> p <- "1087.003489"
>> as.numeric(p, digits=6)
> [1] 1087.003
>
> I would be nice if I could keep all the decimal places after the conversion.
>
> Thanks,
>
> Roger
>


-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list