Hi I wanted to ask a question related to the question asked in this post. Apologies for reposting the same question but I'm not able to post comments.
Basically, I've tried to use the formula provided in this link, as well as the janitor function to do my rounding.
But it seems for certain numbers, my rounding is not happening correctly.
This are the functions I'm using.
Variation 1:
specify_decimal <- function(x,k) trimws(format(round_half_up(x, k), nsmall=k))
Variation 2:
specify_decimal <- function(x,k) trimws(format(round2(x, k), nsmall=k))
round2 = function(x, n) {
posneg = sign(x)
z = abs(x)*10^n
z = z + 0.5 + sqrt(.Machine$double.eps)
z = trunc(z)
z = z/10^n
z*posneg
}
Code: specify_decimal(data,4)
Data | Expected Result | Actual Result |
---|---|---|
205622666.19065 | 205622666.1907 | 205622666.1906 |
410498564.18375 | 410498564.1838 | 410498564.1837 |
79625403.62595 | 79625403.6260 | 79625403.6259 |
4704482.76615 | 4704482.7662 | 4704482.7661 |
54681256.56625 | 54681256.5663 | 54681256.5662 |
I'm trying to format my numbers to a specific decimal placing (in this case its 4 dp) and I want to round up if the 5th decimal is a 5, for most numbers this formula seems work fine, but I'm not too sure why it doesn't seem to work for these few numbers.
Would really appreciate some advise.
Thank you.