go语言int、string、float类型之间转换
程序员文章站
2024-03-18 21:11:46
...
package main
import (
"strconv"
"fmt"
)
func main() {
test1:="123"
num:=HF_Atoi(test1)
fmt.Printf("字符转换为数字:%d\n",num)//输出123
str:=HF_Itoa(num)
fmt.Printf("数字转换为字符:%v\n",str)//输出123
flat:="123.456"
flat32:= HF_Atof(flat)
fmt.Printf("字符转换为float32:%v\n",flat32)//输出123.456
flat64:= HF_Atof64(flat)
fmt.Printf("字符转换为float64:%v\n",flat64)//输出123.456
str_f32:= HF_Atos(float64(flat32),32)
fmt.Printf("float32转换为字符:%v\n",str_f32)//输出1.23456E+02
str_f64:= HF_Atos(flat64,64)
fmt.Printf("float64转换为字符:%v\n",str_f64)//输出1.23456E+02
}
//! 字符串转数字
func HF_Atoi(s string) int {
num, _ := strconv.Atoi(s)
return num
}
//! 数字转字符串
func HF_Itoa(s int) string {
num:= strconv.Itoa(s)
return num
}
//! 字符串转float32
func HF_Atof(s string) float32 {
num, _ := strconv.ParseFloat(s, 32)
return float32(num)
}
//! 字符串转float64
func HF_Atof64(s string) float64 {
num, _ := strconv.ParseFloat(s, 64)
return num
}
//!float转换为字符串
func HF_Atos(s float64,f int) string{
num:= strconv.FormatFloat(s, 'E', -1, f)
return num
}