如何在Golang中将字符串切片转换为浮点数切片 [英] How to convert slice of string to slice of float in Golang
本文介绍了如何在Golang中将字符串切片转换为浮点数切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将一段字符串转换为浮点数,但结果不是一段。有没有办法将字符串片段中的元素转换为浮点64以返回浮点64片段?
func main() {
a := []string{"20.02", "30.01"}
fmt.Println("This is a single slice of string:", a)
for i, element := range a {
element, _ := strconv.ParseFloat(element, 64)
//This result converts each element to float64 but no longer holds them in a slice.
fmt.Printf("%v, %v
", i, element)
}
}
去游乐场:https://go.dev/play/p/LkNzgvDJw7u
推荐答案
创建float64
的切片并向其追加每个元素。
package main
import (
"fmt"
"strconv"
)
func main() {
a := []string{"20.02", "30.01"}
fmt.Println("This is a single slice of string:", a)
// Creates a float64 slice with length 0 and capacity len(a)
b := make([]float64, 0, len(a))
for _, element := range a {
element, _ := strconv.ParseFloat(element, 64)
b = append(b, element)
}
fmt.Println(b)
}
这篇关于如何在Golang中将字符串切片转换为浮点数切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文