JAVA-number and string (two) string conversion

Number to string

Method 1: Use the static method valueOf of the String class
Method 2: Box the basic type into an object first, and then call the toString of the object

String.vlaueof(variable name)

Integer object.toString()

public class TestNumber {
    
    
	public static String getType(Object o) {
    
    
		return o.getClass().toString();
	}
	public static void main(String args[]) {
    
    
		int i =5;
		System.out.println(getType(i));
		
		
		String a = String.valueOf(i);//方法一
		System.out.println(getType(a));

		Integer it = i;
		String name = it.toString();//方法二
		System.out.println(getType(name));
	}
}

String to number

Integer.parseInt (variable name) method

public class TestNumber {
    
    
	public static String getType(Object o) {
    
    
		return o.getClass().toString();
	}
	public static void main(String args[]) {
    
    
		String a = "500";
		
		int b = Integer.parseInt(a);
		System.out.println(getType(b));
		System.out.println(b);
	}
}

Exercise-string conversion

public class TestNumber {
    
    
	public static String getType(Object o) {
    
    
		return o.getClass().toString();
	}
	public static void main(String args[]) {
    
    
		float a = 3.14f;
		
		String b = String.valueOf(a);
		System.out.println(getType(b));
		
		float a1 = Float.valueOf(b);
		System.out.println(getType(a1));
	}
}

Universal conversion:

int a = 1;
String a1 = String.valueOf(a);

String a = "100";
int a1 = Integer.valueOf(a);

float a = 3.14;
String a1 = String.valueOf(a);

String a = "3.14";
float a1 = Float.valueOf(a);

Guess you like

Origin blog.csdn.net/qq_17802895/article/details/108712885