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

自古美人都是妖i 提交于 2019-12-18 15:52:26

问题


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

回答1:


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

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

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).




回答2:


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:

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('\0', ' ');

  return (emptyString + numberString);
}

Input:

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));
}

Output:

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



回答3:


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

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);
}


来源:https://stackoverflow.com/questions/16946694/how-do-i-align-the-decimal-point-when-displaying-doubles-and-floats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!