Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java formatting, negative values, zero padding

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

like image 857
Deragon Avatar asked Sep 03 '12 18:09

Deragon


2 Answers

\u0054 is d

You can do

((i < 0) ? "-" : "") + String.format("%03d", Math.abs(i)); 
like image 153
Peter Lawrey Avatar answered Oct 17 '22 07:10

Peter Lawrey


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

like image 43
Chochos Avatar answered Oct 17 '22 05:10

Chochos