5

In Java, I have the following code:

System.out.printf("%05.5f", myFloat);

This works well for any numbers which are less than 10, but for any number 10 or greater, the decimal places are trimmed to 5, but that doesn't compensate for the fact that the number before the decimal point is longer. I'd like to do one of the following:

12.3456
1.23456

(ie, the same number of digits), or:

12.34567
 2.34567

(ie, pad with spaces so that the decimal points and last digits line up).

I'd be happy if I could get either to work (both would be even better!).

Any thoughts? Thanks!

4
  • 1
    Do you know the maximum width you will need? If so, just use that as the width instead of 5. Commented Jul 10, 2013 at 18:47
  • You mean like "%05f"? If so, that doesn't work. I get: 29.979748 and then 7.449038 (same number of digits after the decimal point, but no leading spaces or 0s). Commented Jul 10, 2013 at 18:49
  • I mean line "%08.5f" -- make it wider Commented Jul 10, 2013 at 20:06
  • Yeah, I eventually figured out to do that. See @marko-topolnik's comment on my answer. Commented Jul 10, 2013 at 20:30

1 Answer 1

7

I figured out how to get it to do:

12.34567
 2.34567

Given a format string like "%x.yf", it will format with minimum width x, and post-decimal-point precision y. Since the pre-decimal point digits and the decimal point itself count towards the minimum width (x), the width has to be at least two larger than the precision. In particular, if a number is printed which is wider than the minimum width, it will not line up nicely with adjacent lines since those lines will be shorter. For example, if we try printing 10.1 and then 1.1 with a width of 3 and a precision of 1, we will get:

10.1
1.1

However, if we use a width of 4, 1.1 will be padded because it's not of the minimum width:

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

4 Comments

...and now you can understand Ted Hopp's comment :)
I couldn't get this to work it just wasn't padding the number the way I wanted. I ended up using two string.format calls String.format("%%%5s", String.format("%2.2f", number)) to get the formatting I was expecting.
Could you say what numbers you were using?
It's sometimes also useful to write %-x,yf if you want the spaces to be padded to the right (this doesn't align the decimal point, but it does produce fixed width columns)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.