将整数转换为浮点数

如何将整数值转换为 float64类型?

我尽力了

float(integer_value)

但是这不工作。而且找不到任何包,这样做的 Golang.org

如何从整数值得到 float64值?

179739 次浏览

没有 float类型。看起来你想要 float64。如果只需要单精度浮点值,也可以使用 float32

package main


import "fmt"


func main() {
i := 5
f := float64(i)
fmt.Printf("f is %f\n", f)
}

为了完整起见,这里是 一个描述所有类型的 Golang 文档的链接。在你的例子中是数字类型:

uint8       the set of all unsigned  8-bit integers (0 to 255)
uint16      the set of all unsigned 16-bit integers (0 to 65535)
uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)


int8        the set of all signed  8-bit integers (-128 to 127)
int16       the set of all signed 16-bit integers (-32768 to 32767)
int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)


float32     the set of all IEEE-754 32-bit floating-point numbers
float64     the set of all IEEE-754 64-bit floating-point numbers


complex64   the set of all complex numbers with float32 real and imaginary parts
complex128  the set of all complex numbers with float64 real and imaginary parts


byte        alias for uint8
rune        alias for int32

这意味着您需要使用 float64(integer_value)

类型转换 T (),其中 T是结果的期望数据类型,在 GoLang 中非常简单。

在我的程序中,我从用户输入扫描一个整数 ,对它执行类型转换并将它存储在变量 F中。输出输出 float64等效于 int输入。float32数据类型也可在 GoLang 获得

密码:

package main
import "fmt"
func main() {
var i int
fmt.Println("Enter an Integer input: ")
fmt.Scanf("%d", &i)
f := float64(i)
fmt.Printf("The float64 representation of %d is %f\n", i, f)
}

解决方案:

>>> Enter an Integer input:
>>> 232332
>>> The float64 representation of 232332 is 232332.000000

直觉 ToFloat32

// ToFloat32 converts a int num to a float32 num
func ToFloat32(in int) float32 {
return float32(in)
}


// ToFloat64 converts a int num to a float64 num
func ToFloat64(in int) float64 {
return float64(in)
}

正确放置括号是关键:

package main


import (
"fmt"
)


func main() {


var payload uint32
var fpayload float32
payload = 1320
    

// works
fpayload = float32(payload) / 100.0
fmt.Printf("%T = %d, %T = %f\n", payload, payload, fpayload, fpayload)
    

// doesn't work
fpayload = float32(payload / 100.0)
fmt.Printf("%T = %d, %T = %f\n", payload, payload, fpayload, fpayload)
}

结果:

Uint32 = 1320,float32 = 13.200000

Uint32 = 1320,float32 = 13.000000

围棋游乐场

做这些

package main


func main(){
a:= 70
afloat := float64(a)
fmt.Printf("type of a is %T\n", a) // will int
fmt.Printf("type of a is %T\n", afloat) //will float64
}