How to convert a float to an int in Golang

Last updated on Aug 3, 2022 by Suraj Sharma



In this tutorial, you will learn how you can convert a float value to an int value in golang


Directly assigning a float64 value to an int variable throws a compile time error,


Cannot use 'a' (type float64) as type int

Therefore, there is a different way to type cast float to int in golang

Here’s a working example in golang to convert a float64 or float32 to an int


package main

import "fmt"

func main() {
    var a float64
    var c float32
    a = 2.34566
    c = 4.5
    var b, d int

    b = int(a)
    d = int(c)


    fmt.Printf("int value of a float64 is %d \n", b)
    fmt.Printf("int value of c float32 is %d", d)
}


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.