String.format won't allow int
I was looking for a quick way to format an int to a string with two leading zeros. I found this StackOverflow answer and it looked exactly the way I needed it. So I implemented it as such
int i = 34; //could be any value but you get the idea
String.format("%03d", i);
But it seems Eclipse is moaning because String.format is required for the second parameter Object[]
. What's going on here?
source to share
If you want to print the value i
, you can use:
System.out.printf("%03d", i);
instead
System.out.println(String.format("%03d", i));
EDIT:
Also I tried my code in Java 6 and it didn't work. So, I used printf ().
OU. Sorry! I cleaned the project and it worked.
I am using Java 6 and Eclipse Helios.
source to share
The following compiles and works under Java 7 (and Eclipse Juno SR1 is happy with it):
public class Main {
public static void main(String[] args) {
int i = 42;
System.out.println(String.format("%03d", i));
}
}
The error message is a red herring: although the last argument Object...
(aka Object[]
), auto-boxing takes care of everything.
I suspect you are using an outdated version of Java and / or Eclipse, or the compiler compliance level in your Eclipse project is set to pre-1.5 (even if you are using 1.5+).
source to share
String s = String.format ("% 04d", i);
This code stands for 4 digits in the number of lines, so .. if u use% 04d, I get two breaks of zeros in front
Although int i is primitive and its expecting object as an argument,
its JVM will internally take care of converting to object datatype
see this according to java implementation.
public static String format(String format, Object ... args) {
return new Formatter().format(format, args).toString();
}
Sample code to add zeros dynamically ...
import java.text.DecimalFormat; public class ArrayTest {
public static void main(String[] args) {
int i = 34; //could be any value but you get the idea
int zeroCount = 2;
String s = String.format("%d", i);
int length = s.length()+zeroCount;
System.out.println(String.format("%0"+length+"d", i));
// second way u can achieve
DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setMinimumIntegerDigits(length);
System.err.println(decimalFormat.format(i));
}
}
And coming to the System.format arguments it might take an infinite number. parameters as your varargs object as second parameter
Check out this url http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#format%28java.lang.String,%20java.lang.Object...%29
source to share