How to convert int to float in Golang?

Golang data types have to be explicitly converted from one to another. There is no implicit conversion in the Go language from smaller to larger data types as in other programming languages like Java. This post will look at how we can convert an int data type to a float data type.

Let’s look at both of them one by one

Converting int to float32 data type

We can easily convert an int to float by using the explicit conversion as shown by the below program.

package main

import (
	"fmt"
	"reflect"
)

func main() {

	var a1 int = 45
	var f float32 = float32(a1)

	fmt.Println("Type of f is", reflect.TypeOf(f))
	fmt.Println("Value of f is", f)
}

Output –

Type of f is float32
Value of f is 45

We have used the TypeOf() method of the reflect package to know the type of the variable passed into the function’s argument. Here, we have converted the int to a float32 data type by using the float32() method.

Converting int to float64 data type

Similarly, we can also convert the int value to float64 as well.

package main

import (
	"fmt"
	"reflect"
)

func main() {

	var a1 int = 45
	var f float64 = float64(a1)

	fmt.Println("Type of f is", reflect.TypeOf(f))
	fmt.Println("Value of f is", f)
}

Output –

Type of f is float64
Value of f is 45
int to float conversion in java

Please remember to use the correct function with the correct data type, we can use float64() with a float32 data type

package main

import (
	"fmt"
	"reflect"
)

func main() {

	var a1 int = 45
	var f float32 = float64(a1)

	fmt.Println("Type of f is", reflect.TypeOf(f))
	fmt.Println("Value of f is", f)
}

Output –

.\main.go:11:6: cannot use float64(a1) (type float64) as type float32 in assignment

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected].

Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *