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

4

3 回答 3

8

\u0054 is d

You can do

((i < 0) ? "-" : "") + String.format("%03d", Math.abs(i)); 
于 2012-09-03T18:54:05.370 回答
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).

于 2012-09-03T19:12:23.397 回答
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.

于 2021-08-10T03:01:16.527 回答