How to only show two decimal points without rounding

Viewed 450

For a value like 0.999942062, I would like to show this value as 0.99 without rounding to 1. For that, I tried the following functions:

x <- 0.999942062
round(x, 2)
formatC(x, 2)
sprintf(x, fmt = '%#.2f')

They all result in 1. Do you know how to print it like 0.99?

4 Answers

You could use substr() converted into "character" beforehand.

substr(as.character(0.999942062), 1, 4)
# [1] "0.99"

Use trunc(x * 10^n) / 10^n as you want to simply truncate your number (effectively rounding it towards 0)

also floor(x * 10^n) / 10^n would archieve the same for positive numbers

Edit:

changed floor and trunc usage as I had memorized them wrongly as @Sotos and @Roland pointed out

x = c(0.999942062, 20)
gsub("(.*)(\\.)(.{2}).*", "\\1\\2\\3", x)
#[1] "0.99" "20"  

if your number could have varying number of digits to the left of the decimal point, you'll want to use regexpr inside of substr after converting to character to locate the decimal point and then add two digits to the end. Like so:

substr(as.character(10.999462), 1, regexpr("\\.", as.character(10.999462)) + 2)

Related