user3466776
user3466776

Reputation: 41

Formatting String output

I am trying to format strings so that it prints out with a width of three always and ending at the same line despite how large the number is. Every number but one is a decimal below ten; however, when I print the one above ten that is a decimal the width is four and ends past the last digit of the previous numbers. I would like to make it so that they all end at the same spot and line up on the right by that. How can I do this using printf in Java?

[a 4.34]
[b 0.32]
[c 12.52]

I would like each of those to line up like so

[a 4.34]
[b 0.32]
[c 12.5]

Here is what I already have for the line that prints

for(int i = 0; i < 26;i++)
{
    System.out.printf("[%c %3.2f]\n", letters[i], frequencies[i]);
}

Thanks!

Upvotes: 0

Views: 5790

Answers (3)

Gurgadurgen
Gurgadurgen

Reputation: 408

If you want to make the resulting width vary based on the widest row, go with the answer user1544460 gave, or just define multiple print statements with the same if-then-else structure. If you always want the width to be the same (max for all), you need to specify more digits in your formatted string.

"%3.2f" means "I want a number that has at LEAST 3 spaces TOTAL, TWO of which I want to go toward its value after the decimal point."

Change

System.out.printf("[%c %3.2f]\n", letters[i], frequencies[i]);

to

System.out.printf("[%c %5.2f]\n", letters[i], frequencies[i]);

Assuming the maximum value has 3 digits left of the decimal point.

If you want it to work dynamically, and resize to fit the largest row, do this:

if(maxNum >= 100)
    System.out.printf("[%c %5.2f]\n", letters[i], frequencies[i]);
else if(maxNum >= 10)
    System.out.printf("[%c %4.2f]\n", letters[i], frequencies[i]);
else // If we get here, we've either coded something wrong, or it's less than 10.
    System.out.printf("[%c %3.2f]\n", letters[i], frequencies[i]);

Upvotes: 1

user1544460
user1544460

Reputation: 193

Assuming numbers are always less than 100

private static DecimalFormat df1digit = new DecimalFormat("0.00");
private static DecimalFormat df2digit = new DecimalFormat("#.00");
private static DecimalFormat df3digit = new DecimalFormat("##.0");

You can compare you number with 10 and 1 use the relevant decimal format. You can extend this idea to format millions, billions etc.

if(x>10){
    System.out.println(df3digit.format(x));
}else if(x>1){
    System.out.println(df2digit.format(x));
}else{
    System.out.println(df1digit.format(x));
}

0 in format string will handle pure integers if there are any so that you will always get same length of numbers.

Upvotes: 0

k_g
k_g

Reputation: 4464

Replace

System.out.printf("[%c %3.2f]\n", letters[i], frequencies[i]);

with

System.out.printf("[%c %3.3g]\n", letters[i], frequencies[i]);

"g" means significant figures rather than places after the decimal point, so 3 is used.

For more information, see the Javadoc for the formatter.

Upvotes: 0

Related Questions