How do I convert a float in the format of xxxxxxxe+09 to an int in Go?

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

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不返回相同的结果,它返回一个float64float32。在使用它之后,你可以像通常一样将其转换为整数:

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

英文:

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

答案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!

huangapple
  • 本文由 发表于 2014年7月24日 00:40:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/24916224.html
匿名

发表评论

匿名网友

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

确定