John Balvin Arias
John Balvin Arias

Reputation: 2896

unformat string number with thousand comma golang

I have this string "1,090"

I want to convert it to float

v := "1,090"
s, err := strconv.ParseFloat(v, 32)
if  err != nil {
    fmt.Printf("err: %s\n", err)
    return
}
fmt.Printf("%T, %v\n", s, s)

But it returns an error:

//err: strconv.ParseFloat: parsing "1,090": invalid syntax

So anybody know to convert it to float?

Upvotes: 0

Views: 2255

Answers (1)

nightfury1204
nightfury1204

Reputation: 4654

The reason it is failed because "1,090" has , comma in it. You have to remove the , from the string before you use strconv.ParseFloat(v, 32). One way to remove comma is by using strings.Replace():

v := "1,090"

v = strings.Replace(v, ",", "", -1)

s, err := strconv.ParseFloat(v, 32)
if  err != nil {
        fmt.Printf("err: %s\n", err)
        return
}
fmt.Printf("%T, %v\n", s, s)

Upvotes: 5

Related Questions