-2

Is there a way to round the number 4.25 to 4.3 instead of 4.2 in R?

x <- sprintf("%-8.1f",4.25) # rounds it to 4.2
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • 1
    Does this answer your question? [Round up from .5](https://stackoverflow.com/questions/12688717/round-up-from-5) – Lukas Kaspras Feb 27 '21 at 00:05
  • @Sudha: You've already gotten 2 downvote (neither of them mine) so some friendly advice: if you want to avoid further downvotes and get the question reopened on the basis of your comments to the answer below, you should show your efforts at coding that demonstrates that you have read the nominated duplicate and made efforts to adapt it to your needs. – IRTFM Feb 27 '21 at 02:58

1 Answers1

1

If you like you can write your own "round" function like below

fround <- function(x, d = 0) {
  x.abs <- abs(x)
  s <- sign(x)
  u <- trunc(x.abs * 10^d)
  s * (u + ifelse(x.abs * 10^d - u >= 0.5, 1, 0)) / 10^d
}

such that

> fround(4.25, 2)
[1] 4.25

> fround(4.25, 1)
[1] 4.3

> fround(4.25, 0)
[1] 4

> fround(-4.25, 2)
[1] -4.25

> fround(-4.25, 1)
[1] -4.3

> fround(-4.25, 0)
[1] -4
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • Thank you so much Thomas. Probably I should have put my question right. Function work +4.25 which is rounded to 4.3 but not for -4.25 which also needs to be rounded -4.3 – Sudha Feb 27 '21 at 01:54
  • Also +4.23 should be rounded to 4.2. But when using fround function above it is being rounded to +4.3. – Sudha Feb 27 '21 at 02:19
  • 1
    @Sudha You have this code and the code in the nominated duplicate, so why not show that you have learned to make modifications for cases that might be a bit more complex that what you asked for. If _and_ _only_ _if_ you still need help after making a good faith effort at revising these approachs, then [edit] your question to include a data example that includes other cases under consideration and what you desire for an answer to those cases. – IRTFM Feb 27 '21 at 03:02
  • @Sudha See my update – ThomasIsCoding Feb 27 '21 at 16:16