Round down a numeric
Asked Answered
M

3

14

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?

Mart answered 1/10, 2016 at 1:47 Comment(0)
I
31

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
Impious answered 1/10, 2016 at 3:22 Comment(0)
D
2

You misunderstand the issue. If the value is in -1.542045, it will always be.

Now you can print it to two decimals or get a two decimal char:

> print(a, digits=3)
[1] -1.54
> format(a, digits=3)
[1] "-1.54"
> 

Should you really desire to create a new representation you can:

> b <- trunc(a*1e2)*1e-2
> b
[1] -1.54
> 

A preferable way may be

> b <- round(a, digits=2)
> b
[1] -1.54
> 
Dorena answered 1/10, 2016 at 1:50 Comment(0)
P
2

A combination of ceiling(), abs() and sign() can be used to round up the abs of the number, irrespective of its sign. Such a rounding at two decimal digits can be obtained with:

ceiling(abs(a)*100)/100*sign(a)

Example:

a <- c(-1.542045, 1.542045)
ceiling(abs(a)*100)/100*sign(a)
#[1] -1.55  1.55
Prytaneum answered 1/10, 2016 at 7:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.