2

I have to round a data frame to two decimal places and the 1/100s decimal always needs to round up. However I am seeing some odd behavior with the ceiling function that I'm using.

a <- c(268.600, 268.700, 268.500)
b <- c(22.410, 653.423, 124.400)

df1 <- data.frame(a, b)

ceiling(df1 * 100)/100

       a      b
1 268.61  22.41
2 268.70 653.43
3 268.50 124.40

I expect the output at df1[1,1] to be 268.60 .. but I am getting 268.61. I am not sure why this is happening; the other numerics in 'a' give the expected output. I'm using R version 3.5.3

EDIT:

@Akrun identified the issue in col A as a result of floating point numbers.

What I am looking for help with now is a way to round a number like 10.032 to 10.04 while also avoiding having a number like 10.000 round to 10.01 due to floating point issues.

Right now I am stuck with either having df1[1,1] round correctly or df[2,2] round correctly but not both.

  • 1
    The reason is that it a floating point number and not exactly integer `(df1$a * 100) == 26860#[1] FALSE FALSE FALSE`. or to find the difference `(df1$a * 100)- 26860 [1] 3.637979e-12 1.000000e+01 -1.000000e+01#` – akrun Aug 01 '19 at 16:06

1 Answers1

3

It is not exactly an integer, so it is not. equal to 26860

(df1$a * 100)- 26860
#[1]  3.637979e-12  1.000000e+01 -1.000000e+01

which gets rounded with ceiling

To avoid that, we can convert to integer

ceiling(as.integer(df1$a * 100))/100
#[1] 268.6 268.7 268.5
akrun
  • 874,273
  • 37
  • 540
  • 662
  • This solves the issue with floating point numbers in col a, however it then removes the functionality I need that impacts col b. For example, I'd need 10.032 to round up to 10.04 but using as.integer() in the middle of the process removes the decimal I am trying to round up: e <- 10.032 f <- e * 100 g <- as.integer(f) h <- ceiling(g) i <- h/100 I think what I need is to find something that works like the ms Decimal type :( – Jake Mercer Aug 02 '19 at 14:23
  • @JakeMercer. sorry, that was not your original question – akrun Aug 02 '19 at 14:24
  • @JakeMercer. Your question is not clear now. if you can either post as a new question (if it is totally different) or update the post (if it is similar). I spend some time on this – akrun Aug 02 '19 at 14:29
  • thank you for your help. I have tried to clarify the question. – Jake Mercer Aug 02 '19 at 15:00
  • @JakeMercer. I can't reproduce the issue. Can you provide an example `v1 <- c(10.032, 10.000, 10.0001); ceiling((v1 *100))# [1] 1004 1000 1001` – akrun Aug 02 '19 at 16:02