基本类型转换

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

一、字符类转化为整型

  • 字符串转double:
string s = "124";    double x = Double.parseDouble(s);
  • 字符串转float:
string s = "124";   float f = Float.parseFloat(s);
  • 字符串转int:
string s = "124";   int i = Float.parseFloat(s);
  • 字符串转short:
string s = "124";   short sh = Short.parseFloat(s);
  • 字符串转long:
string s = "124";   long l = Long.parseLong(s);
  • 字符串转byte:
string s = "124";   byte b = Long.parseByte(s);
  • 字符串转char:
String s = "1";
char c = s.charAt(0);
  • char转字符串
char c = 'a';
String s = String.valueOf(c);
  • char

二、数字类型转字符串

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转其他类型

//其它类型同下
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 数值类型转二进制

//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类型与数值转换

//a~z 97~122
//A~Z 65~90
char c = 97;
System.out.println(c);

int a = '9' - '0';
System.out.println(a);
posted @ 2020-10-07 01:05  云卷云舒c  阅读(122)  评论(0编辑  收藏  举报