2

This is pretty straight forward:

> sprintf("%013d",150025901)
[1] "0000150025901"
> sprintf("%013d",8150025901)
Error in sprintf("%013d", 8150025901) : 
  invalid format '%013d'; use format %f, %e, %g or %a for numeric objects

ultimately I need to use this on a 12 digit number, but I just removed digits until sprintf would stop returning that error.

Stephen K
  • 697
  • 9
  • 26
  • 2
    I'm not sure, but I think it's because `%d` is for integer values and `is.integer(8150025901) ## [1] FALSE` and `is.double(8150025901) ## [1] TRUE`. At some point the large integer is no longer an integer in R. But like I said, I don't know for sure. – Rich Scriven Sep 16 '15 at 15:43
  • 3
    on my (and, I suspect most R systems) `.Machine$integer.max` == `2147483647` so you're definitely in `double` territory and out of `d` use. – hrbrmstr Sep 16 '15 at 15:46
  • Confirmed `.Machine$integer.max < 8150025901 ## [1] TRUE`. So you may need to switch to `format()` instead of `sprintf()` – Rich Scriven Sep 16 '15 at 15:47
  • 1
    Try `library(stringr); str_pad(8150025901, 13, pad = "0")` – zx8754 Sep 16 '15 at 15:50
  • 4
    possible duplicate of [adding leading zeros using R](http://stackoverflow.com/questions/5812493/adding-leading-zeros-using-r) – zx8754 Sep 16 '15 at 15:50

1 Answers1

5

8150025901 is too big for an integer, which maxes out at 2147483647

You can use sprintf with a double instead of an int and get the desired results. The exact code for this would be:

sprintf("%013.000f",8150025901)

However, it is important to note that--while R will not give you an explicit error or warning--if you try to do this with numbers more than ~15 digits, you can get unpredictable results.

This is because doubles in R have 53-bit precision, and 10^15 < 2^53 < 10^16. That means the rounding error in the number you are converting is greater than one for 16-digits, so (for example) sprintf("%013.000f",10^16) and sprintf("%013.000f",10^16+1) both produce "10000000000000000" due to rounding

Frank
  • 544
  • 2
  • 14