Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format number as fixed width, with leading zeros [duplicate]

Tags:

format

r

printf

People also ask

How can I pad a value with leading zeros?

To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.

How do you add a leading zero in R?

Add Leading Zeros to the Elements of a Vector in R Programming – Using paste0() and sprintf() Function. paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument.


There are several solutions to this.

One of them is to use sprintf. This uses C style formatting codes embedded in a character string to indicate the format of any other arguments passed to it. For example, the formatting code %3d means format a number as integer of width 3:

a <- seq(1,101,25)
sprintf("name_%03d", a)
[1] "name_001" "name_026" "name_051" "name_076" "name_101"

Another is formatC and paste:

paste("name", formatC(a, width=3, flag="0"), sep="_")
[1] "name_001" "name_026" "name_051" "name_076" "name_101"