How can I tell R to round correctly?
Decimal Places in R I have encountered a problem that I cannot figure out how to solve I want R to calculate 5/26*100 = 19.230769
x <- 5/26*100
x
gives me:
[1] 19.23077
Let's try to use round(), first setting the digits to 4:
x <- round(5/26*100,digits=4)
x
gives:
[1] 19.2308
Next, let's set the digits to 5:
x <- round(5/26*100,digits=5)
x
gives:
[1] 19.23077
Now, let's set the digits to 6:
x <- round(5/26*100,digits=6)
x
gives:
[1] 19.23077
Can anyone tell me how to fix this? Do you get the same results, or does your rstudio round correctly?
I have also tired signif()
x <- signif(5/26*100,digits=6)
x
gives us:
[1] 19.2308
increasing to 7 digits:
> x <- signif(5/26*100,digits=7)
> x
[1] 19.23077
Increasing to 8 digits:
> x <- signif(5/26*100,digits=8)
> x
[1] 19.23077
And we can use sprintf()
> x <- sprintf("%0.6f", (5/26*100))
> x
[1] "19.230769"
sprintf() solves the problem with rounding, but it creates a new problem by changing the numeric value to a character.
Can anyone show me how to get r to give me 5/26*100 = 19.230769 with a numeric output?
Thank you,
Drew