I have a function that passes a number to different rounding functions depending on a category. For example, if my function is applyRoundRule
, and if the category is A, I might pass the number 2.415 to a rounding function that might round up from 5 with the expected result 2.42.
My problem is if I input the number directly into the function call it works fine, but if I pass in a function or variable that determines the number R appears to conduct its own rounding resulting in the wrong result, 2.41 in the above case.
For instance, if I write
applyRoundRule("A", (1 + 15/100)*2.1)
The answer is
2.41
Similarly, if write
applyRoundRule("A", signif((1 + 15/100)*(100 - 97.9),4))
I get the right answer (2.42) but in other instances I get the wrong answer, in other words without signif
certain values will be wrong and with another set of numbers will be wrong.
What can I do such that R doesn't conduct it's own rounding prior to my designated rounding rules?
Edit: Please find an example of the two relevant functions
applyRoundRule <- function(categ, num){
roundVal <- switch(categ,
"A" = RoundUp(num,2),
"B" = RoundUp(num,3)
)
return(roundVal)
}
And the rounding function might be something like
RoundUp = function(x, n) {
z = abs(x)*10^n
z = z + 0.5
z = trunc(z)
z = z/10^n
}