How to Convert Float to Integer in Golang?

In the Go programming language, you can convert a float value into an integer through the int() function. In this article, we will learn it by an example, let’s begin with importing the required packages into the go file.

import (
    "fmt"
    "reflect"
)

Reflect provides a ValueOf() and Kind() method that chains together and converts float value into an integer. After importing the required packages, initialize a variable with a float value.

var cyclePrice float32 = 120.50

Before converting its data type, let’s check its current data type and assigned value.

fmt.Println(cyclePrice)
// Output: 120.5

fmt.Println(reflect.ValueOf(cyclePrice).Kind())
// Output: float32

After running the above code, it is confirmed that the cyclePrice variable has a float value that needs to convert into an integer. To do that pass the cyclePrice variable as an argument into the int() function.

// convert float into integer
var convertIntoInteger int = int(cyclePrice)

The int() function converts the float value to an integer. You can also assign it to a new variable as above. Next, let’s print convertIntoInteger variable data type and value to check if the int() function worked correctly.

fmt.Println(convertIntoInteger)
// Output: 120

// check data type of variable
fmt.Println(reflect.ValueOf(convertIntoInteger).Kind())
// Output: int

We got exactly the same value that we were expecting. At the end of this article, we would like to share the complete code.

package main
import (
    "fmt"
    "reflect"
)

func main() {

  var cyclePrice float32 = 120.50
  
  fmt.Println(cyclePrice)
  // Output: 120.5
  
  fmt.Println(reflect.ValueOf(cyclePrice).Kind())
  // Output: float32
  
  // convert float into integer
  var convertIntoInteger int = int(cyclePrice)
  
  fmt.Println(convertIntoInteger)
  // Output: 120
  
  // check data type of variable
  fmt.Println(reflect.ValueOf(convertIntoInteger).Kind())
  // Output: int

}

Conclusion

This article demonstrates steps for converting float values into integers through the int() function.


Related Posts