Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 703
Uncle Iroh Avatar asked Jun 05 '13 17:06

Uncle Iroh


2 Answers

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

like image 192
Uncle Iroh Avatar answered Sep 22 '22 02:09

Uncle Iroh


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)
like image 25
Djon Avatar answered Sep 23 '22 02:09

Djon