英文:
How to convert slice of string to slice of float in Golang
问题
我正在尝试将字符串切片转换为浮点数,但结果不是切片。有没有办法将字符串切片中的元素转换为float64,并返回一个float64切片?
func main() {
a := []string{"20.02", "30.01"}
fmt.Println("这是一个字符串切片:", a)
var result []float64
for _, element := range a {
value, _ := strconv.ParseFloat(element, 64)
result = append(result, value)
}
fmt.Println("这是一个float64切片:", result)
}
Go playground: https://go.dev/play/p/LkNzgvDJw7u
英文:
I am trying to convert a slice of string into float but the result isn't a slice. Is there a way to convert the elements within a slice of string to float64 to return a slice of float64?
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\n", i, element)
}
}
Go playground: https://go.dev/play/p/LkNzgvDJw7u
答案1
得分: 5
创建一个float64
类型的切片,并将每个元素追加到其中。
package main
import (
"fmt"
"strconv"
)
func main() {
a := []string{"20.02", "30.01"}
fmt.Println("这是一个字符串切片:", a)
// 创建一个长度为0,容量为len(a)的float64切片
b := make([]float64, 0, len(a))
for _, element := range a {
element, _ := strconv.ParseFloat(element, 64)
b = append(b, element)
}
fmt.Println(b)
}
英文:
Create a slice of float64
and append each element to it.
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论