5

Here's a quote from: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html

'd' '\u0054' Formats the argument as a decimal integer. The localization algorithm is applied.

If the '0' flag is given and the value is negative, then the zero padding will occur after the sign.

I feel frustrated, trying to learn this formatting thing but that tutorial is just so cluttered and messy.

String.format("%03d", int); 

I am trying to understand where exactly this whole \u0054 should go but I have just no idea, I must be missing something very obvious or something...

Edit:

What I want to achieve: Positive 10: 010 Negative 10: -10 Negative result I want to achieve: -010

1
  • 1
    '\u0054' is equivalent to 'd' Commented Sep 3, 2012 at 18:55

3 Answers 3

9

\u0054 is d

You can do

((i < 0) ? "-" : "") + String.format("%03d", Math.abs(i)); 
Sign up to request clarification or add additional context in comments.

2 Comments

If I just keep it the way I have now, the negative (-) replaces a zero so: positive 10: 010 for example, but the negative would be -10 but I want it to say -010
@Deragon something close which maintains consistency should be "%+04d" which will produce "+010" and "-010".
7

Try String.format("% 4d", i) then (with a space between % and 4); it's using 4 positions, zero-padded and it leaves an extra space for positive values, so you get " 010" and "-010". You can trim() the string afterwards to get rid of the initial space (or do something like if (i>0) s=s.substring(1) or something).

2 Comments

I like this answer. It gives proper padding for non-negative values. You need a "% 04d" to maintain the proper number of leading zeros, though.
Shouldn't it be String.format("% 04d", i)?
0

The following works

public class MyProgram
{
    public static void main(String[] args)
    {
        int n = -13754;
        int p = 2234;
        String buffer = String.format("%08d", n);
        System.out.println(buffer);
        buffer = String.format("%08d", p);
        System.out.println(buffer);
    }
}

output

-0013754
00002234

For your example "%03d" is what you would use.

Comments

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.