Ryan Rodrigues
Ryan Rodrigues

Reputation: 35

How to convert slice of string to slice of float in Golang

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

Upvotes: 1

Views: 1390

Answers (1)

super
super

Reputation: 12928

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

Upvotes: 5

Related Questions