英文:
How do I convert a float in the format of xxxxxxxe+09 to an int in Go?
问题
在Golang中,你可以使用strconv库将类似1.400126761e+09的数字转换为int类型。你可以尝试使用strconv.ParseFloat函数将其转换为float64类型,然后再将其转换为int类型。以下是一个示例代码:
package main
import (
"fmt"
"strconv"
)
func main() {
number := "1.400126761e+09"
floatNum, err := strconv.ParseFloat(number, 64)
if err != nil {
fmt.Println("Error:", err)
return
}
intNum := int(floatNum)
fmt.Println(intNum)
}
这段代码将输出整数形式的结果。你可以根据需要进行调整和修改。希望对你有帮助!
英文:
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?
答案1
得分: 2
只需使用int()。例如:
x := float32(3.1)
fmt.Println(int(x))
英文:
Just use int(). For example:
x := float32(3.1)
fmt.Println(int(x))
答案2
得分: 1
ParseFloat
不返回相同的结果,它返回一个float64
或float32
。在使用它之后,你可以像通常一样将其转换为整数:
s := "1.400126761e+09"
f, err := strconv.ParseFloat(s, 64)
if err == nil {
thisisanint := int(f)
fmt.Println(thisisanint)
} else {
fmt.Println(err)
}
英文:
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)
}
答案3
得分: 0
我之前并没有清楚地表达,我正在处理的变量使用了interface{},在将其转换为int()之前,只需要进行float64类型断言即可。希望这能帮到你!
英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论