如何将 Int 转换为给定长度的字符串,前导零对齐? [英] How to convert an Int to a String of a given length with leading zeros to align?

查看:13
本文介绍了如何将 Int 转换为给定长度的字符串,前导零对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 Int 转换为 7 字符长的 String,使 123 变成 "0000123"?

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

推荐答案

Java 库已经相当不错了(和优秀一样)数字格式支持,可从 StringOps 丰富的字符串类:

The Java library has pretty good (as in excellent) number formatting support which is accessible from StringOps enriched String class:

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

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

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

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

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

2019 年 4 月

  • 如果您想要前导空格而不是零,只需从格式说明符中省略 0.在上述情况下,它将是 f"$expr%7d".在 2.12.8 REPL 中测试.无需按照评论中的建议进行字符串替换,甚至无需按照另一条评论中的建议在 7 前面放置一个明确的空格.
  • 如果长度可变,s"%${len}d".format("123")
  • If you want leading spaces, and not zero, just leave out the 0 from 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 7 as suggested in another comment.
  • If the length is variable, s"%${len}d".format("123")

这篇关于如何将 Int 转换为给定长度的字符串,前导零对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆