string转float64:

1
2
3
4
5
6
import "strconv"

tmp := ""
str, err := strconv.ParseFloat(tmp, 64)
fmt.Println(str) // 0 float64类型
// 当tmp="asdsad"时,str会为0,但err会有错误产生

string转bool:

1
value, _ := strconv.ParseBool("asdasd")  // 当报错时值为false

string转int或int64:

1
2
3
4
5
strInt, _ := strconv.Atoi("0")  // 当报错时值为0
fmt.Println(strInt)

strInt64, _ := strconv.ParseInt("0", 10, 64)
fmt.Println(strInt64)

int或int64转成string:

1
2
string := strconv.Itoa(int)
string := strconv.FormatInt(int64,10)

bool转string:

1
boolStr := strconv.FormatBool(true)

float64转string:

1
2
3
4
5
import "strconv"

tmp := 0.00
aa := strconv.FormatFloat(tmp, 'f', 2, 64) // 0.00 string类型,保留两位小数
fmt.Println(aa)

float64向上、向下取整

1
2
3
4
5
6
7
8
import (
"fmt"
"math"
)

x := 1.1
fmt.Println(math.Ceil(x)) // 2
fmt.Println(math.Floor(x)) // 1

float64转int,并四舍五入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
“fmt”
“math”
)

func main(){
x:= 3.1415
//四舍五入
c:=int(math.Ceil(x-0.5))
d:=int(math.Floor(x+0.5))
fmt.Println(“c”,“d”,c,d)
}
# c、d结果都是3

float64四舍五入 && int数值计算转float,并保留两位小数(四舍五入):

1
2
3
4
5
var devicesTotal float64 = 0.00
deviceTotal:=524152832
deviceTotalFloat64, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", float64(deviceTotal)/1024/1024), 64)
devicesTotal = devicesTotal + deviceTotalFloat64
fmt.Println(devicesTotal) // 499.87

string转化为struct对象:

1
2
3
4
5
6
7
import "encoding/json"

type ClusterAddDTO struct {
// ...省略
}

_ = json.Unmarshal([]byte("...省略"), &clusterAddDTO)

数组转字符串,用逗号分隔:

1
2
3
4
data := []string{"l", "i", "c", "h", "u", "a", "c", "h", "u", "a"}
str := strings.Join(data, ",")
fmt.Println(str)
# 结果:l,i,c,h,u,a,c,h,u,a