Keeping 2 digits after decimal without rounding off

Viewed 160

data <- c(28.9899,23.565444,98.8999,34.8788)

The expected output is: 28.98, 23.56, 98.89, 34.87

5 Answers

Basic R floor function doesn't allow decimal number so let's define

floor_decimal <- function(x, level=1) round(x - 5*10^(-level-1), level)

then by

floor_decimal(data,2)

returns

[1] 28.98 23.56 98.89 34.87

Assuming this is for displaying purpose you may use regex to extract data only till 2 decimal places.

sub('(\\d+\\.\\d{2}).*', '\\1', data)
#[1] "28.98" "23.56" "98.89" "34.87"

Cut unwanted digits using regex and re-convert to numeric:

as.numeric(sub("(.*\\.\\d{2}).*", "\\1", data))
[1] 28.98 23.56 98.89 34.87

We could use trunc():

trunc(data*100)/100

Output:

[1] 28.98 23.56 98.89 34.87
library(stringi)
data<- c(28.9899,23.565444,98.8999,34.8788) 
as.numeric(stri_sub(data,1,5))

output

28.98 23.56 98.89 34.87
Related