How to align decimal point when displaying paired and floats

If I have the following decimal 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 

I want:

  1.123 12.423 0.123 123.344 1.100 
+8
java double number-formatting
source share
3 answers

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

4 represents the length of the whole number (including decimal), and not just the part preceding the decimal. 3 represents the number of decimal places.

So, to get the format accurate to 4 numbers to decimal and 3 decimal places, the required format is actually String.format("%8.3f", number) .

+8
source share

Here is 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); } 
+2
source share

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

If all of them are 4.3f , we can assume that each number will contain up to 8 characters, so we can do this:

 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) 
+1
source share

All Articles