在Golang中将整数转换为浮点数

115 go

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

我试过了

float(integer_value)
Run Code Online (Sandbox Code Playgroud)

但这不起作用.并且在Golang.org上找不到任何这样做的包.

如何从整数值中获取float64值?

zmb*_*zmb 156

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

package main

import "fmt"

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

  • 让我们注意 go 的编译器对此并不直观。`a := uint(8); b := uint(5); c := float32(a/b)` 将使 `c` 为 1.00000,而不是 1.6。 (2认同)

Sal*_*ali 32

仅仅为了完整起见,这里是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
Run Code Online (Sandbox Code Playgroud)

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


小智 7

就做这些

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
}
Run Code Online (Sandbox Code Playgroud)