如何在Golang中将字符串切片转换为浮点数切片

huangapple go评论74阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2022年2月27日 22:18:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/71285485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定