To convert an int
type value to any float
type value in Go or Golang, you can either use the float32()
or the float64()
built-in functions depending upon the size you need to allocate for it.
For example, let's say we need to convert an int
value of 3000
to a float
type value.
Converting int
to float32
type
Let's say we need to allocate only a 32-bit
size for it, so we can use the float32()
built-in function and pass the int
value as an argument to the function like this,
package main
import "fmt"
func main() {
// an `int` type value
intNum := 3000
// convert `int` to `float32`
// using the `float32()` function
float32Num := float32(intNum)
// log to the console
fmt.Println(float32Num) // 3000 and the type is `float32`
}
As you can see from the above code the int
type value of 3000
is converted into a float32
type value.
Converting int
to float64
type
If we need to allocate a 64-bit
size, then we can use the float64()
built-in function and pass the int
value as an argument to the function like this,
package main
import "fmt"
func main() {
// an `int` type value
intNum := 3000
// convert `int` to `float64`
// using the `float64()` function
float64Num := float64(intNum)
// log to the console
fmt.Println(float64Num) // 3000 and the type is `float64`
}
As you can see from the above code the int
type value of 3000
is converted into a float64
type value.
Note: If you need to learn more about types in Go, see the blog on What are the basic types in Go or Golang?.
See the above codes live in The Go Playground.
That's all 😃!