将数字格式化为固定宽度,前导零 [英] Format number as fixed width, with leading zeros
本文介绍了将数字格式化为固定宽度,前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码
a <- seq(1,101,25)
b <- paste("name", 1:length(a), sep = "_")
产生这个输出:
"name_1" "name_26" "name_51" "name_76" "name_101"
我希望所有值的宽度相同,这意味着我用零填充值,如下所示:
I'd like to have the same width of all values which means for me to fill the values with zeros like this:
"name_001" "name_026" "name_051" "name_076" "name_101"
我该如何处理?
(这个问题与这个问题有关.)
推荐答案
有几种解决方案.
其中之一是使用 sprintf
.这使用嵌入在字符串中的 C
样式格式代码来指示传递给它的任何其他参数的格式.例如,格式化代码 %3d
表示将数字格式化为宽度为 3 的整数:
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"
另一个是formatC
和paste
:
paste("name", formatC(a, width=3, flag="0"), sep="_")
[1] "name_001" "name_026" "name_051" "name_076" "name_101"
这篇关于将数字格式化为固定宽度,前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文