1

我有以下代码:

buffer := make([]byte, 256)
conn.Read(buffer)

result:= string(buffer)
fmt.Println("Val:", result)

floatResult, _ := strconv.ParseFloat(result, 64)
fmt.Println("Val on float:", floatResult)

输出如下:

Val: 40.385167
Val on float: 0

这似乎是将字符串解析为float64's 的正确方法,有什么我遗漏的吗?

4

1 回答 1

1

您可以创建具有len等于读取字节数的新切片(查看Reader

buffer := make([]byte, 256)
i, _ := conn.Read(buffer) // i  number of read bytes 

result:= string(buffer[:i]) // create new slice with 'len' equals number of read bytes
fmt.Println("Val:", result)

floatResult, _ := strconv.ParseFloat(result, 64)
fmt.Println("Val on float:", floatResult)

PLAYGROUND (io.Reader stub)

于 2020-11-25T05:39:27.333 回答