To convert a set of strings to a set of floats in Go, you can use the strconv
package's ParseFloat()
function to transform each string value into its corresponding float value.
In this example,
stringSlice1
with values []string{"1.1", "2.2", "3.3"}
.stringSlice1
using a for
loop.strconv.ParseFloat()
function to convert each string value to a float. We handle any errors that may occur during the conversion process.floatSlice1
.package main
import (
"fmt"
"strconv"
)
func main() {
stringSlice1 := []string{"1.1", "2.2", "3.3"}
var floatSlice1 []float64
for _, s := range stringSlice1 {
f, err := strconv.ParseFloat(s, 64)
if err == nil {
floatSlice1 = append(floatSlice1, f)
}
}
fmt.Println(floatSlice1)
}
[1.1 2.2 3.3]
In this example,
stringSlice2
with values []string{"4.5", "5.6", "6.7"}
.stringSlice2
using a for
loop.strconv.ParseFloat()
function to convert each string value to a float. We handle any errors that may occur during the conversion process.floatSlice2
.package main
import (
"fmt"
"strconv"
)
func main() {
stringSlice2 := []string{"4.5", "5.6", "6.7"}
var floatSlice2 []float64
for _, s := range stringSlice2 {
f, err := strconv.ParseFloat(s, 64)
if err == nil {
floatSlice2 = append(floatSlice2, f)
}
}
fmt.Println(floatSlice2)
}
[4.5 5.6 6.7]
In this tutorial, we learned How to Convert a Set of Strings to a Set of Floats in Go language with well detailed examples.