 2013-10-07 16:41

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

How do I convert an integer value to `float64` type?

I tried

``````float(integer_value)
``````

But this does not work. And can't find any package that does this on Golang.org

How do I get `float64` values from integer values?

• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 4条回答默认 最新

• douhui4831 2013-10-07 16:44
已采纳

There is no `float` type. Looks like you want `float64`. You could also use `float32` if you only need a single-precision floating point value.

``````package main

import "fmt"

func main() {
i := 5
f := float64(i)
fmt.Printf("f is %f
", f)
}
``````
点赞 评论
• dongzipu7517 2015-05-08 07:25

Just for the sake of completeness, here is a link to the golang documentation which describes all types. In your case it is numeric types:

``````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
``````

Which means that you need to use `float64(integer_value)`.

点赞 评论
• douchongbc72264 2018-09-15 19:56

Type Conversions T() where T is the desired datatype of the result are quite simple in GoLang.

In my program, I scan an integer i from the user input, perform a type conversion on it and store it in the variable f. The output prints the `float64` equivalent of the `int` input. `float32` datatype is also available in GoLang

Code:

``````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
", i, f)
}
``````

Solution:

``````>>> Enter an Integer input:
>>> 232332
>>> The float64 representation of 232332 is 232332.000000
``````
点赞 评论
• duangou1933 2018-09-18 15:12

intutils.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)
}
``````
点赞 评论