java 显示双精度数和浮点数时如何对齐小数点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16946694/
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-11-01 00:28:07  来源:igfitidea点击:

How do I align the decimal point when displaying doubles and floats

javadoublenumber-formatting

提问by Uncle Iroh

If I have the following decimal point numbers:

如果我有以下小数点数字:

Double[] numbers = new Double[] {1.1233, 12.4231414, 0.123, 123.3444, 1.1};
for (Double number : numbers) {
    System.out.println(String.format("%4.3f", number));
}

Then I get the following output:

然后我得到以下输出:

1.123
12.423
0.123
123.344
1.100

What I want is:

我想要的是:

   1.123
  12.423
   0.123
 123.344
   1.100

采纳答案by Uncle Iroh

The part that can be a bit confusing is that String.format("4.3", number)

可能有点令人困惑的部分是 String.format("4.3", number)

the 4represents the length of the entire number(including the decimal), not just the part preceding the decimal. The 3represents the number of decimals.

4表示整个数(包括小数)的长度,而不仅仅是小数之前的部分。该3代表的小数位数。

So to get the format correct with up to 4 numbers before the decimal and 3 decimal places the format needed is actually String.format("%8.3f", number).

因此,要在小数点前最多 4 个数字和 3 个小数位获得正确的格式,所需的格式实际上是String.format("%8.3f", number).

回答by Djon

You can write a function that prints spaces before the number.

您可以编写一个在数字前打印空格的函数。

If they are all going to be 4.3f, we can assume that each number will take up to 8 characters, so we can do that:

如果它们都是4.3f,我们可以假设每个数字最多占用 8 个字符,所以我们可以这样做:

public static String printDouble(Double number)
{
  String numberString = String.format("%4.3f", number);
  int empty = 8 - numberString.length();
  String emptyString = new String(new char[empty]).replace('
public static void main(String[] args)
{
    System.out.println(printDouble(1.123));
    System.out.println(printDouble(12.423));
    System.out.println(printDouble(0.123));
    System.out.println(printDouble(123.344));
    System.out.println(printDouble(1.100));
}
', ' '); return (emptyString + numberString); }

Input:

输入:

run:
   1,123
  12,423
   0,123
 123,344
   1,100
BUILD SUCCESSFUL (total time: 0 seconds)

Output:

输出:

Double[] numbers = new Double[]{1.1233, 12.4231414, 0.123, 123.3444, 1.1};

for (Double number : numbers) {
  System.out.printf("%7.3f\n", number);
}

回答by A-SM

Here's another simple method, user System.out.printf();

这是另一个简单的方法,用户 System.out.printf();

##代码##