12

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 

3 Answers 3

12

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

Sign up to request clarification or add additional context in comments.

Comments

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) 

Comments

2

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

4 Comments

It's actually %8.3f, at least on my computer.
It depends on the output format length I think, 123.344 its length is about 7, it's the minimum you should reserve in your printf format.
I think the first number means the total of characters to use, but I'm not sure.
Yes, something like that, I also have the same thought.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.