当前位置:网站首页>Basic data types and string types are converted to each other

Basic data types and string types are converted to each other

2022-07-07 08:32:00 Jimmy_ jimi

Basic data type string

Method 1 :fmt.Sprintf format

import "fmt"

func main() {
    
	var num1 int = 99
	var num2 float64 = 123.12
	var b bool = true
	var myChar byte = 'h'
	
	//int  To  string
	str := fmt.Sprintf("%d", num1)
	fmt.Printf("str type : %T , str=%q", str, str)

	//float64  To  string
	str = fmt.Sprintf("%f", num2)
	fmt.Printf("str type : %T , str=%q", str, str)

	//bool  To  string
	str = fmt.Sprintf("%t", b)
	fmt.Printf("str type : %T , str=%q", str, str)

	//byte  To  string
	str = fmt.Sprintf("%c", myChar)
	fmt.Printf("str type : %T , str=%q", str, str)
}

// str type : string , str="99"
// str type : string , str="123.120000"
// str type : string , str="true"
// str type : string , str="h"

Method 2 :strconv Function of the package

import (
	"fmt"
	"strconv"
)

func main() {
    
	var num1 int = 99
	var num2 float64 = 123.12
	var b bool = true
	var myChar byte = 'h'

	// Mode one 、int  To  string
	str := strconv.FormatInt(int64(num1), 10)
	fmt.Printf("str type : %T , str=%q", str, str)

	// Mode two 、int  To  string
	str = strconv.Itoa(num1)
	fmt.Printf("str type : %T , str=%q", str, str)

	//float64  To  string
	str = strconv.FormatFloat(num2, 'f', 10, 64)
	fmt.Printf("str type : %T , str=%q", str, str)

	//bool  To  string
	str = strconv.FormatBool(b)
	fmt.Printf("str type : %T , str=%q", str, str)

	//byte  To  string
	//str = strconv.Itoa(int(myChar))
	str = string(myChar)
	fmt.Printf("str type : %T , str=%q", str, str)
}

// str type : string , str="99"
// str type : string , str="99"
// str type : string , str="123.1200000000"
// str type : string , str="true"
// str type : string , str="h"

string Type to basic data type

package main

import (
	"fmt"
	"strconv"
)

func main() {
    
	var num1 string = "99"
	var num2 string = "123.12"
	var b string = "true"

	// string  To  int64
	//10  Represents the hexadecimal after output ,2-32 Base number 
	// here 64 Is the limit bit , Not the data type of the specified output , in fact strconv.ParseInt Only return int64 Type data ,bitesize The limit is the data size , If the transformed shaping data num1 exceed 127, that err It will show that the data is out of range ( Report errors (variable of type int64) as type int in argument to fbn Cause analysis ).
	str, _ := strconv.ParseInt(num1, 10, 64)
	fmt.Printf("str type: %T str=%d", str, str)

	// string  To  float64
	number, _ := strconv.ParseFloat(num2, 64)
	fmt.Printf("str type: %T str=%f", number, number)

	// string  To  bool
	ret, _ := strconv.ParseBool(b)
	fmt.Printf("str type: %T str=%t", ret, ret)
}

原网站

版权声明
本文为[Jimmy_ jimi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070526597235.html