golang

How to convert float to int in Golang


In this article, you are going to learn about how to convert a float64 number into an integer in Golang.

In Golang, datatypes are very strict which means if you declare a variable type as float64 you can not write any other value except float number. If you try to write an integer number into a float64 type declared variable, you will simply get an error.

But you can convert a float64 number into an integer. To perform this action, you have to do this manually. Follow the below code example:

package main

import "fmt"

func main() {
        var x float64 = 12.15
        var y int = int(x)

        fmt.Printf("The Type of y: %T\\n", y)

        y2 := int(x)
        fmt.Printf("The Type of y2: %T\\n", y2)
}

/* Output:

        The Type of y: int
        The Type of y2: int

*/

Here, we import our required packages and then explicitly convert the float64 into an integer type. You can see the output where the type is indicating int.

This is how you can convert a float64 type into an integer type in GoLang.


Share on social media

//