John
John

Reputation: 1947

Setting maximum numbers of characters in number

I want to have number with respect to maximum number of characters. e.g. let's take value 517.1918

I want to set that maximum number of characters to three, then it should give mu just 517 (just three first characters)

My work so far

I tried so split my number into to parts : first one containing three first numbers and second one containing remaining numbers by a code following :

d_convert<-function(x){
  x<-sub('(.{3})(.{2})', '\\1', x)
  x
}
d_convert(12345) 

And it work's, but I'm not sure how can I put instead of (.{2}), length(x)-3. I tried print(paste()) but it didn't work. Is there any simply way how to do it ?

Upvotes: 1

Views: 101

Answers (2)

Jilber Urbina
Jilber Urbina

Reputation: 61214

I'm not sure if I understood what want, but you can try this:

d_convert2 <-function(x, digits=3){
  x <- gsub("\\D", "", x)
  num_string <- strsplit(x, "")[[1]]
  out <- list(digits = num_string[1L:digits], renaming = num_string[(digits+1):length(num_string)])
  out <- lapply(out, paste0, collapse="")
  return(out)
}


> d_convert2(12345)
$digits
[1] "123"

$renaming
[1] "45"

> d_convert2("1,234.5")
$digits
[1] "1" "2" "3"

$renaming
[1] "4" "5"

Upvotes: 1

Max Feinberg
Max Feinberg

Reputation: 840

Try using signif which rounds a number to a given number of significant digits.

> signif(517.1918, 3)
[1] 517

Upvotes: 1

Related Questions