Anna
Anna

Reputation: 895

Is there a function in R that can round down OR up to an integer?

Wondering if there an exists a function that can round a number up or down as I noticed that

as.integer(5.99999)

gives me 5, so it looks like as.integer coerces a numeric to an integer by dropping any number after the decimal place. Thank you!

Upvotes: 8

Views: 8762

Answers (2)

B_Heidel
B_Heidel

Reputation: 64

Adding some remarks to the answer from Sescopeland.

Everyone must be careful when using the round() function since it does not do what many people expect to do.

The function precisely returns the closest EVEN numbers! For example, round(1.5) would produce 2 but also round(2.5) would produce 2 as well!

Please check out the Details section of the ?round().

Upvotes: 3

Sescopeland
Sescopeland

Reputation: 325

The round() function works great. You can do the following to get a result of 6:

as.integer(round(5.99999))

If you want it to round up or down, use the ceiling() or floor() functions, respectively, in place of the round() function. Ex:

as.integer(ceiling(5.9999))

Upvotes: 9

Related Questions