golang中string int float bool類型相互轉換


golang中string int float bool類型相互轉換

package main

import (
	"fmt"
	"strconv"
)

func IntToString() {
	//todo :int to string
	v := 456
	vS := strconv.Itoa(v)
	fmt.Println(vS) //方法1,簡便版

	//todo :int64 to string
	var vI64 int64 = 789
	vInt64S := strconv.FormatInt(vI64, 10) //方法2,int64轉string,可指定幾進制
	fmt.Println(vInt64S)

	//todo :uint64 to string
	var vUI64 uint64 = 91011
	vUI64S := strconv.FormatUint(vUI64, 10) //方法3, uint64轉string,可指定幾進制
	fmt.Println(vUI64S)
}

func StringToInt() {
	//todo :string to int/int64
	s := "123"
	vInt, _ := strconv.Atoi(s) //方法1,便捷版
	fmt.Println(vInt)

	vInt64, _ := strconv.ParseInt(s, 10, 64) //方案2,有符號整型,可以指定幾進制,整數長度
	fmt.Println(vInt64)

	vUInt64, _ := strconv.ParseUint(s, 10, 64) //方案3,無符號整型,可以指定幾進制,整數長度
	fmt.Println(vUInt64)
}

func StringToFloat() {
	//todo :string to float
	f64, _ := strconv.ParseFloat("123.456", 64) //方法1,可以指定長度
	fmt.Println(f64)
}

func FloatToString() {
	//todo :float to string
	f64 := 1223.13252
	sF64 := strconv.FormatFloat(f64, 'f', 5, 64) //方法1,可以指定輸出格式、精度、長度
	fmt.Println(sF64)
}

func StringToBool() {
	//todo :string to bool
	 接受 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False 等字符串;
	 其他形式的字符串會返回錯誤
	b, _ := strconv.ParseBool("1")
	fmt.Println(b)
}
func BoolToString() {
	//todo :bool to string
	sBool := strconv.FormatBool(true) //方法1
	fmt.Println(sBool)
}

func main() {
	StringToInt()
	IntToString()
	StringToFloat()
	FloatToString()
	BoolToString()
	StringToBool()
}
  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM