[英]Convert int which start with leading zero to string
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. 我正在尝试将以0开头的int转换为存储在电话目录中的字符串,因为电话号码可以从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
. 每次我得到输出0085
而不是0125
。
How do I convert an int with a leading zero to a string in decimal format? 如何将带前导零的int转换为十进制格式的字符串?
An int
value starting with a zero is considered to be a octal number
(having numbers from 0 - 7) similar to hexadecimal numbers. 以零开头的int
值被认为是类似于十六进制数的octal number
(具有0到7的数字)。 Hence your value: 因此你的价值:
0125
is equal to: 1 * 8 2 + 2 * 8 1 + 5 * 8 0 == 64 + 16 + 5 == 85 等于: 1 * 8 2 + 2 * 8 1 + 5 * 8 0 == 64 + 16 + 5 == 85
Don't try to represent a phone-number as an int
. 不要试图将电话号码表示为int
。 Instead use a String
and validate it using a regex expression. 而是使用String
并使用正则表达式验证它。 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
. regex
只是匹配电话号码的示例,如: 1234
或0123-45678
。
A numeric literal that starts with 0
is considered to be Octal (base 8). 以0
开头的数字文字被认为是八进制(基数为8)。 125 base 8 is 85 base 10 (decimal). 125 base 8是85 base 10(十进制)。
Also, int i = 09
will throw a compiler error for the same reason. 此外, int i = 09
将因同样的原因抛出编译器错误。
See 09 is not recognized where as 9 is recognized 见9未被识别,因为9被识别
0125
is actually 85. Why? 0125
实际上是85.为什么?
Numbers that starts with 0, are octal numbers. 以0开头的数字是八进制数。 So 0125 is: 所以0125是:
5*8 0 + 2*8 1 + 1*8 2 = 85 5 * 8 0 + 2 * 8 1 + 1 * 8 2 = 85
See the JLS - 3.10.1. 参见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. 八进制数字由ASCII数字0后跟一个或多个散布有下划线的ASCII数字0到7组成,并且可以表示正整数,零整数或负整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.