Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to float32?

Tags:

go

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

I have tried using:

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

But it does not work. This is the error I get:

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

Is there anything else I could do? Thanks!

like image 334
Gambit2007 Avatar asked Apr 03 '16 21:04

Gambit2007


People also ask

Can you convert string to float Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number.

How do you get a float out of a string?

For converting strings to floating-point values, we can use Float. parseFloat() if we need a float primitive or Float. valueOf() if we prefer a Float object.

Can I convert string to float in Java?

We can convert String to float in java using Float. parseFloat() method.

How do you convert a string to a real number in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .


1 Answers

float has the type float32, but strconv.ParseFloat returns float64. All you need 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 the situation, it may be better to change float's type to float64.

like image 181
Tim Cooper Avatar answered Oct 08 '22 03:10

Tim Cooper