将整数转换为浮点数

新手上路,请多包涵

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

我试过了

float(integer_value)

但这不起作用。并且在 Golang.org 上找不到执行此操作的任何包

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

原文由 user2671513 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 478
2 个回答

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

 package main

import "fmt"

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

原文由 zmb 发布,翻译遵循 CC BY-SA 3.0 许可协议

为了完整起见,这里有 一个指向描述所有类型的 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)

原文由 Salvador Dali 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题