如何将数字打印为Java中特定空间的数字?

发布于 2025-02-08 14:56:11 字数 173 浏览 2 评论 0原文

我想在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温柔嚣张 2025-02-15 14:56:11

尝试一下,其中格式由代码中定义的一些“长度”确定:

double x = 5.2375484914759291;
int length = 8;
String format = "%."+length+"f";
System.out.printf(format,x);
//5.23754849 is the output for printf("%.8f",5.2375484914759291)

通过将格式字符串连接到您的数字变量,您可以指定格式。这是将int格式化的宽度的示例:

int y = 247;
int width = 8;
String formatWidth ="%0" + width + "d";
System.out.printf(formatWidth,y);
//00000247 is the output for printf("%08d",247)

将其扩展到格式化长度和宽度:

double z = 247.7526;
int length = 2;
int width = 8;
String formatBoth = "%0" + width + "." + length + "f";
System.out.printf(formatBoth,z);
//00247.75 is the output for printf("%08.2f",247.7526)

您也可以通过将长度和宽度声明为字符串变量来使用格式字符串,具体取决于您的代码。

Try this, where your formatting is determined by some 'length' defined in the code:

double x = 5.2375484914759291;
int length = 8;
String format = "%."+length+"f";
System.out.printf(format,x);
//5.23754849 is the output for printf("%.8f",5.2375484914759291)

By concatenating formatting strings to your number variable, you can specify the formatting. Here is an example of formatting the width for an int:

int y = 247;
int width = 8;
String formatWidth ="%0" + width + "d";
System.out.printf(formatWidth,y);
//00000247 is the output for printf("%08d",247)

Extending this to format both length and width:

double z = 247.7526;
int length = 2;
int width = 8;
String formatBoth = "%0" + width + "." + length + "f";
System.out.printf(formatBoth,z);
//00247.75 is the output for printf("%08.2f",247.7526)

You could also play around with your formatting string by declaring length and width as String variables, depending on your code.

呆头 2025-02-15 14:56:11

只需使用串联构建字符串

int x = 8;
System.out.printf("%" + x + ".1f\n", 1.123);

Simply build the string with concatenation

int x = 8;
System.out.printf("%" + x + ".1f\n", 1.123);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文