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!
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.
Related
Using type assertion doesn't work to convert interface{} to float32
package main
import (
"fmt"
)
func main() {
var i interface{}
i = 1.1
num, ok := i.(float32)
fmt.Println(ok)
fmt.Println(num)
}
https://play.golang.org/p/iEJWLbBCHs8
This prints false and 0. How can I convert interface{} to float32?
When the code runs:
i = 1.1
It assigns a float64 value to the variable i; that's the default type for decimal number literals in Go. When you try to convert it to float32, it fails because that's not the underlying type of i.
If you want to convert i to float32, you need to put a float32 value in it:
i = float32(1.1)
And the conversion will succeed. If you want to be able to convert to float32 or float64, you can try converting to both types, and if the conversion to float64 succeeds, you then convert the result to float32.
To answer your question:
How can I convert interface{} to float32?
Not at all.
All you can do is store a float32 in an interface{} and then type-assert it out back again. The problem with your code is that you do not store a float32.
Can someone point me in the right direction of this Go's syntax :
(*int)(nil)
If I have a a value of a given type and I want to convert it to, lets say, float64 I can do this :
var num int = 65
fnum := float64(num)
If I have an interface and I want to "cast it" to some type I can do this :
func main() {
concretevalue := dosomething("hello!")
fmt.Printf("%T : %v", concretevalue, concretevalue)
}
func dosomething( v interface{} ) string {
return v.(string)
}
Where does the (*int)(nil) fit? How can I get information about this specific syntax?
It is a type-conversion, same as float64(num), however, because the converted type is a pointer, you need extra parentheses, because otherwise *int(nil) would mean converting nil to int, and then dereferencing it.
I have a function that simply reads a file with ioutil.ReadFile(). The type returned is []byte, although the value itself can be represented as a float.
I am converting the []byte in this manner (where value is the []byte being returned from a function that reads a file):
var floatValue float64
fmt.Fscanf(bytes.NewReader(value), "%f", &floatValue)
Is this really the only way to extract/parse a valid float value from a []byte? There's a similar discussion but looks like it didn't really go anywhere.
You can easily use strconv.ParseFloat for this, just converting your []byte to a string first. This would surely have less overhead than creating a reader and scanning with a scanf-like function.
sb := []byte("3.1415")
s := string(sb)
f, err := strconv.ParseFloat(s, 64)
if err != nil {
panic("whoops!")
}
fmt.Printf("%f\n", f)
Output:
3.141500
I've just started learning Go and I'm trying to convert a string from standard input to a float64 so I can perform an arithmetic operation on the input value.
The output returns "0 feet converted to meters gives you 0 meters" regardless of the input value. I can't figure out why the value is zero after invoking ParseFloat on the input.
If someone could please point out to me why this is happening, I would greatly appreciate it.
const conversion float64 = 0.3048
func feetToMeters (feet float64) (meters float64) {
return feet * conversion
}
func main(){
fmt.Println("\n\nThis program will convert feet to meters for you!\n")
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter feet value: \n")
feet, _ := reader.ReadString('\n')
feetFloat, _ := strconv.ParseFloat(feet, 64)
meters := feetToMeters(feetFloat)
fmt.Printf("%v feet converted to meters give you %v meters",feetFloat,meters)
}
The problem is that you try to parse "x.x\n", e.g: 1.8\n. And this returns an error: strconv.ParseFloat: parsing "1.8\n": invalid syntax. You can do a strings.TrimSpace function or to convert feet[:len(feet)-1] to delete \n character
With strings.TrimSpace() (you need to import strings package):
feetFloat, _ := strconv.ParseFloat(strings.TrimSpace(feet), 64)
Wtih feet[:len(feet)-1]:
feetFloat, _ := strconv.ParseFloat(feet[:len(feet)-1], 64)
Output in both cases:
10.8 feet converted to meters give you 3.2918400000000005 meters
Given a number like 1.400126761e+09 in Golang, what can I use to cast it to an int? I tried using the strconv library to play around with it and convert it using FormatFloat but that function returns the same thing when I give it the 'e' flag. Any other functions/libraries that will handle this conversion to an int?
Just use int(). For example:
x := float32(3.1)
fmt.Println(int(x))
ParseFloat is not returning the same thing, it's returning a float64 or float32. After you use it, you can just convert to an int as usual:
s := "1.400126761e+09"
f, err := strconv.ParseFloat(s, 64)
if err == nil {
thisisanint := int(f)
fmt.Println(thisisanint)
} else {
fmt.Println(err)
}
Go Playground
I actually was not clear as the variable I was playing with employs the interface{} and simply needed a float64 type assertion before casting it like int(). Hope this helps!