Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round down a numeric

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?

like image 656
dan Avatar asked Oct 01 '16 01:10

dan


1 Answers

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
like image 122
Zheyuan Li Avatar answered Sep 30 '22 12:09

Zheyuan Li