将字符串转换为float32类型。

huangapple go评论89阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年4月4日 05:52:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/36391664.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定