Format numeric to two-digits

Viewed 416

I have a column of numeric class, e.g.: v <- c(12345, 2345, 7689900).

I know that every number is actually of the form 12.345, 23.45, 76.89900, ie every numeric has two digits and the rest is decimals.

How can I convert the vector to this format? No decimal should be cropped in the process.

3 Answers

If you are looking for a numeric vector, one option could be:

v/10^(nchar(v) - 2)

[1] 12.345 23.450 76.899

Edit:

In cases when we have more than 20 digits, we can Count the number of integer digits using log10:

v/10^(floor(log10(abs(v))) + 1 - 2)

Using regex we can capture the data in two groups separated by ".".

sub('(..)(.*)', '\\1.\\2', v)
#[1] "12.345"   "23.45"    "76.89900"

You can wrap this in as.numeric if you want to perform some manipulation on this.

as.numeric(paste0(substring(v,1,2), ".", substring(v,3)))
# [1] 12.345 23.450 76.899
Related