Convert string to float32?

There is input that I need to read from the console as a string, then process the string and convert it to float32.

I tried using:

float, _ := strconv.ParseFloat(myString, 32)

But that will not work. This is the error I get:

cannot use float (type float64) as type float32 in value field

Is there anything else I could do? Thank!

+4
source share
1 answer

floathas a type float32but strconv.ParseFloatreturns float64. All you have to do is convert the result:

// "var float float32" up here somewhere
value, err := strconv.ParseFloat(myString, 32)
if err != nil {
    // do something sensible
}
float = float32(value)

Depending on your situtaion, it is better to change the type floatto float64.

+7
source

All Articles