Round down a numeric

dan picture dan · Oct 1, 2016 · Viewed 34.5k times · Source

I have numeric's like this one:

a <- -1.542045

And I want to round them down (or round up the abs) to 2 digits after the decimal point. signif(a,3) will round it down and give me 1.54 as a result but for this example the result I want is -1.55.

Any idea?

Answer

Zheyuan Li picture Zheyuan Li · Oct 1, 2016

I think you are looking for floor(a * 100) / 100.

Quick Test

a <- c(-1.542045, 1.542045)
floor(a * 100) / 100
# [1] -1.55  1.54

I just noticed that you changed your question 7 hours ago. Then my answer is not doing exactly what you want (as I am assuming by "rounding down" you always want to round toward -Inf). But I have discussed this in first version of my answer. Now I am going to copy those relevant back here.

  • With sign(a) * ceiling(abs(a) * 100) / 100 you can round data toward Inf for positive values and -Inf for negative values.
  • With sign(a) * floor(abs(a) * 100) / 100, you round both positive and negative values toward 0.

A quick test

a <- c(-1.542045, 1.542045)

sign(a) * ceiling(abs(a) * 100) / 100
# [1] -1.55  1.55

sign(a) * floor(abs(a) * 100) / 100
# [1] -1.54  1.54