• 字符串与数值类型互转
  • char和String互转
  • 其他类型互转
  • 英文字母与ASCII码数值范围

一、字符类转化为整型

  • 字符串转double:

    1
    string s = "124";    double x = Double.parseDouble(s);
  • 字符串转float:

    1
    string s = "124";   float f = Float.parseFloat(s);
  • 字符串转int:

    1
    string s = "124";   int i = Float.parseFloat(s);
  • 字符串转short:

    1
    string s = "124";   short sh = Short.parseFloat(s);
  • 字符串转long:

    1
    string s = "124";   long l = Long.parseLong(s);
  • 字符串转byte:

    1
    string s = "124";   byte b = Long.parseByte(s);
  • 字符串转char:

    1
    2
    String s = "1";
    char c = s.charAt(0);
  • char转字符串

    1
    2
    char c = 'a';
    String s = String.valueOf(c);
  • char

二、数字类型转字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int a = 127;
String s = String.valueOf(a);
double d = 127;
String s = String.valueOf(d);
……

/**
* Returns the string representation of the {@code Object} argument.
*
* @param obj an {@code Object}.
* @return if the argument is {@code null}, then a string equal to
* {@code "null"}; otherwise, the value of
* {@code obj.toString()} is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}

三、其他类型转换

3.1 Double转其他类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//其它类型同下
public byte byteValue() {
return (byte)value;
}
public short shortValue() {
return (short)value;
}
public int intValue() {
return (int)value;
}
public long longValue() {
return (long)value;
}
public float floatValue() {
return (float)value;
}
public double doubleValue() {
return value;
}

//double 转 int
double d = 127.0;
int i1 = new Double(d).intValue();

//取整
int i2 = Math.ceil(d);
int i3 = Math.floor(d);
int i2 = Math.round(d);

3.2 数值类型转二进制

1
2
3
4
5
6
7
8
9
//int类型
int i = 12;
String s = Integer.toBinaryString(i);
//long类型
long l = 12;
String s = Long.toBinaryString(l);
//short类型
short s = 12;
String st = Short.toBinaryString(s);

3.3 char类型与数值转换

1
2
3
4
5
6
7
//a~z 97~122
//A~Z 65~90
char c = 97;
System.out.println(c);

int a = '9' - '0';
System.out.println(a);