Java self - numeric and string string conversion

Java, the number is converted to a string, the string is converted to digital

Step 1: digital-to-string

Method 1: Use the static method valueOf String class
2: first basic types of packing an object, and then calls the object's toString

package digit;
  
public class TestNumber {
  
    public static void main(String[] args) {
        int i = 5;
         
        //方法1
        String str = String.valueOf(i);
         
        //方法2
        Integer it = i;
        String str2 = it.toString();
         
    }
}

Step 2: String-to-digital

Static method of Integer parseInt call

package digit;
  
public class TestNumber {
  
    public static void main(String[] args) {
 
        String str = "999";
         
        int i= Integer.parseInt(str);
         
        System.out.println(i);
         
    }
}

Exercise : string conversion

See step
floating point numbers are converted to strings 3.14 "3.14"
then the string "3.14" into a floating point 3.14

If the string is 3.1a4, converting what would get to a float?

The answer :

package digit;
 
public class TestNumber {
 
    public static void main(String[] args) {
        float f = 3.14f;
        //浮点数转字符串
        String s = String.valueOf(f);
        //字符串转浮点数
        f= Float.parseFloat(s);
         
        //如果字符串内容不是合法的数字表达,那么转换就会报错(抛出异常)
        Float.parseFloat("3.1a4");
    }
}

Guess you like

Origin www.cnblogs.com/jeddzd/p/11601347.html