Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert []string to []float64 in Golang?

Tags:

go

I'm new to programming, and trying to write a simple average program in Go.

package main

import (
    "fmt"
    "os"
)

var numbers []float64
var sum float64 = 0

func main() {

    if len(os.Args) > 1 {

        numbers = os.Args[1:]

    }

    fmt.Println("Numbers are: ", numbers)
    for _, value := range numbers {
        sum += value
    }

}

http://play.golang.org/p/TWNltPO71N

when I build the program, I got this error:

prog.go:15: cannot use os.Args[1:] (type []string) as type []float64 in assignment
[process exited with non-zero status]

So how to convert a slice of string to a slice of float numbers? Can I map a convert function to the slice?

like image 810
Nick Avatar asked Jan 10 '15 11:01

Nick


2 Answers

You need to convert string to float64 using strconv.ParseFloat function:

package main

import (
    "fmt"
    "os"
    "strconv"
)

var numbers []float64
var sum float64 = 0

func main() {

    if len(os.Args) <= 1 {
        return
    }

    for _, arg := range os.Args[1:] {
        if n, err := strconv.ParseFloat(arg, 64); err == nil {
            numbers = append(numbers, n)
        }
    }

    fmt.Println("Numbers are: ", numbers)
    for _, value := range numbers {
        sum += value
    }

}
like image 74
tumdum Avatar answered Sep 20 '22 06:09

tumdum


It can't convert because string and int are not compatible.

Instead of having the numbers slice, just iterate over os.Args[1:], using ParseFloat from the strconv package.

fmt.Print("Numbers are: ")
for _, arg := range os.Args[1:] {
    fmt.Print(arg, " ")
    value, err := strconv.ParseFloat(arg, 64)
    if err != nil {
        panic(err)
    }
    sum += value
}
like image 31
ThinkChaos Avatar answered Sep 20 '22 06:09

ThinkChaos