0

I try to format integers so they always have four proper digits, that is, I want 0s for padding.

I have tried "%04d" which works nicely for positive number. For negatives it gives things like -[854] where I need -[0854].

Thank you.

Stefan Fischer
  • 363
  • 4
  • 19
  • 2
    can you post code you tried? – Shanu Gupta May 20 '18 at 06:28
  • (you may be confused with the above comment. You can try explaining more, that is, `int i=1;System.out.printf("%04d",i);` instead of just `"%04d"`) – user202729 May 20 '18 at 06:35
  • Also, [instead of "thank you" you can just upvote/accept answers](https://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts)/ – user202729 May 20 '18 at 06:35
  • Possible duplicate of [How do I pad a printf to take account of negative signs and variable length numbers?](https://stackoverflow.com/questions/5325169/how-do-i-pad-a-printf-to-take-account-of-negative-signs-and-variable-length-numb) – user202729 May 20 '18 at 06:38
  • (wait, that's C, but it also works here, use `"% 05d"`, see the 4th flag [here](https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax)) – user202729 May 20 '18 at 06:40

1 Answers1

1
if(number>=0){ 
    String.format("%04d",number); 
}else{
     String.format("%05d",number); 
    }
Abhishek Mishra
  • 611
  • 4
  • 11