string 如何将 Int 转换为给定长度的字符串,并带有前导零以对齐?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8131291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:16:09  来源:igfitidea点击:

How to convert an Int to a String of a given length with leading zeros to align?

stringscalaformattingint

提问by Ivan

How can I convert an Intto a 7-character long String, so that 123is turned into "0000123"?

如何将 an 转换Int为 7 个字符的 long String,从而123变成"0000123"

回答by huynhjl

The Java library has pretty good (as in excellent) number formatting supportwhich is accessible from StringOpsenriched String class:

Java 库具有非常好的(如出色的)数字格式支持,可从StringOps丰富的 String 类访问:

scala> "%07d".format(123)
res5: String = 0000123

scala> "%07d".formatLocal(java.util.Locale.US, 123)
res6: String = 0000123

Edit post Scala 2.10: as suggested by fommil, from 2.10 on, there is also a formatting string interpolator (does not support localisation):

编辑 Scala 2.10 帖子:按照 fommil 的建议,从 2.10 开始,还有一个格式化字符串插值器(不支持本地化):

val expr = 123
f"$expr%07d"
f"${expr}%07d"

Edit Apr 2019:

2019 年 4 月编辑:

  • If you want leading spaces, and not zero, just leave out the 0from the format specifier. In the above case, it'd be f"$expr%7d".Tested in 2.12.8 REPL. No need to do the string replacement as suggested in a comment, or even put an explicit space in front of 7as suggested in another comment.
  • If the length is variable, s"%${len}d".format("123")
  • 如果您想要前导空格而不是零,只需0从格式说明符中删除。在上述情况下,它将f"$expr%7d"在 2.12.8 REPL 中进行 .Tested。无需按照注释中的建议进行字符串替换,甚至无需7按照另一条注释中的建议在前面放置显式空格。
  • 如果长度是可变的, s"%${len}d".format("123")

回答by Pablo Fernandez

Short answer:

简短的回答:

"1234".reverse.padTo(7, '0').reverse

Long answer:

长答案:

Scala StringOps(which contains a nice set of methods that Scala string objects have because of implicit conversions) has a padTomethod, which appends a certain amount of characters to your string. For example:

Scala StringOps(它包含一组很好的方法,Scala 字符串对象由于隐式转换而具有这些padTo方法)有一个方法,它将一定数量的字符附加到您的字符串中。例如:

"aloha".padTo(10,'a')

Will return "alohaaaaaa". Note the element type of a String is a Char, hence the single quotes around the 'a'.

将返回“alohaaaaaa”。请注意,String 的元素类型是 Char,因此'a'.

Your problem is a bit different since you need to prependcharacters instead of appendingthem. That's why you need to reverse the string, append the fill-up characters (you would be prepending them now since the string is reversed), and then reverse the whole thing again to get the final result.

您的问题有点不同,因为您需要预先添加字符而不是附加它们。这就是为什么您需要反转字符串,附加填充字符(由于字符串已反转,您现在将在前面添加它们),然后再次反转整个内容以获得最终结果。

Hope this helps!

希望这可以帮助!

回答by maxmithun

The paddingis denoted by %02dfor 0to be prefixed to make the length 2:

padding是由表示%02d0被前缀以使长度2

scala> val i = 9 
i: Int = 9

scala> val paddedVal = f"${num}%02d"
paddedVal: String = 09

scala> println(paddedVal)             
09

回答by Luigi Plinge

huynhjl beat me to the right answer, so here's an alternative:

huynhjl 击败了我的正确答案,所以这里有一个替代方案:

"0000000" + 123 takeRight 7

回答by zeromem

def leftPad(s: String, len: Int, elem: Char): String = {
 elem.toString * (len - s.length()) + s
}

回答by som-snytt

In case this Q&A becomes the canonical compendium,

如果此问答成为规范纲要,

scala> import java.text._
import java.text._

scala> NumberFormat.getIntegerInstance.asInstanceOf[DecimalFormat]
res0: java.text.DecimalFormat = java.text.DecimalFormat@674dc

scala> .applyPattern("0000000")

scala> res0.format(123)
res2: String = 0000123

回答by 0__

Do you need to deal with negative numbers? If not, I would just do

你需要处理负数吗?如果没有,我只会做

def str(i: Int) = (i % 10000000 + 10000000).toString.substring(1)

or

或者

def str(i: Int) = { val f = "000000" + i; f.substring(f.length() - 7) }

Otherwise, you can use NumberFormat:

否则,您可以使用NumberFormat

val nf = java.text.NumberFormat.getIntegerInstance(java.util.Locale.US)
nf.setMinimumIntegerDigits(7)
nf.setGroupingUsed(false)
nf.format(-123)