when i write
System.out.println(0123);
i get
83
however
System.out.println((int)0123F);
returns
123
why it works that way?
when i write
System.out.println(0123);
i get
83
however
System.out.println((int)0123F);
returns
123
why it works that way?
0123 means octal 123, that is 1*8*8 + 2*8 + 3, which equals 83. For some reason, octal floats are not available.
Creating 0123 means the integer 83. Creating 0123F means the floating 123. When converted back to integer, it remains 123.
Just don't use the leading 0 if you don't mean octal. After all, they are not exactly useful(and programmers who do know about octal numbers will get confused when they see 09F).
Try this:
public static String leftPad(int n, int padding) {
return String.format("%0" + padding + "d", n);
}
leftPad(5, 3); // return "005"
leftPad(15, 5); // return "00015"
leftPad(224, 3); // return "224"
leftPad(0, 4); // return "0000"
printf will do it: http://java.sun.com/developer/technicalArticles/Programming/sprintf/
public class X { public static void main(final String[] argv) { System.out.printf("%04d", 123); System.out.println(); } }
You could also make it "%0" + size + "%d" if you wanted to vary the length... though if the lengths were common I'd probably make constants like: "%04d" "%012d" etc...
The octal (leading 0) and hexadecimal (leading 0x) were inherited from C. For comparison, try
System.out.println(0x123);