如何将数字打印为Java中特定空间的数字?
我想在Java中以格式打印到特定空间的特定空间长度。但是在运行算法时的长度将定义,因此我不能使用直接格式,例如:
system.out.printf(“%8.1f”,number)
例如,lenght“ 8”将会在运行代码时定义了其他地方,如何将其配置以使其自动取决于代码?
I want to print a fractional number into specific length of space with formatting, in Java. But the length will defined while algorithm running, so I can't use straight formatting, such as:
System.out.printf("%8.1f", number)
For example that lenght "8" will defined somewhere else while code running, how can I configure it to make it automatic depends on code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试一下,其中格式由代码中定义的一些“长度”确定:
通过将格式字符串连接到您的数字变量,您可以指定格式。这是将int格式化的宽度的示例:
将其扩展到格式化长度和宽度:
您也可以通过将长度和宽度声明为字符串变量来使用格式字符串,具体取决于您的代码。
Try this, where your formatting is determined by some 'length' defined in the code:
By concatenating formatting strings to your number variable, you can specify the formatting. Here is an example of formatting the width for an int:
Extending this to format both length and width:
You could also play around with your formatting string by declaring length and width as String variables, depending on your code.
只需使用串联构建字符串
Simply build the string with concatenation