I'm trying to convert int's which start with 0 to strings to be stored in a phone directory as the telephone numbers can start with 0.
I've tried -
int num = 0125;
String.format("%04d",num);
and
Integer.toString(num);
and
DecimalFormat df = new DecimalFormat("0000");
df.format(num);
Each time I get the output 0085
rather than 0125
.
How do I convert an int with a leading zero to a string in decimal format?
An int
value starting with a zero is considered to be a octal number
(having numbers from 0 - 7) similar to hexadecimal numbers. Hence your value:
0125
is equal to: 1 * 8 2 + 2 * 8 1 + 5 * 8 0 == 64 + 16 + 5 == 85
Don't try to represent a phone-number as an int
. Instead use a String
and validate it using a regex expression. If you combine both, you may as well represent a phone number by its own type like:
public class PhoneNumber {
private final String number;
public PhoneNumber(String number) {
if (number == null || !number.matches("\\d+([-]\\d+)?")) {
throw new .....
}
this.number = number;
}
}
The regex
is just an example matching phone numbers like: 1234
or 0123-45678
.
A numeric literal that starts with 0
is considered to be Octal (base 8). 125 base 8 is 85 base 10 (decimal).
Also, int i = 09
will throw a compiler error for the same reason.
0125
is actually 85. Why?
Numbers that starts with 0, are octal numbers. So 0125 is:
5*8 0 + 2*8 1 + 1*8 2 = 85
See the JLS - 3.10.1. Integer Literals :
An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.