英文:
Convert string to float32?
问题
有一个输入我需要从控制台读取为字符串,然后操作字符串并将其中的一部分转换为 float32
。
我尝试使用:
float, _ := strconv.ParseFloat(myString, 32)
但是它不起作用。我得到的错误是:
> cannot use float (type float64) as type float32 in field value
我还能做些什么吗?
谢谢!
英文:
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!
答案1
得分: 41
float
类型的实际类型是float32
,但strconv.ParseFloat
返回的是float64
。你只需要将结果进行转换:
// 在某个地方定义变量 "var float float32"
value, err := strconv.ParseFloat(myString, 32)
if err != nil {
// 处理错误
}
float = float32(value)
根据情况,将float
的类型改为float64
可能更好。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论