OneBite.Dev - Coding blog in a bite size

convert variable from float to int in Go

Code snippet on how to convert variable from float to int in Go

  // Define a float variable
  myFloatValue := 1.5
  
  // Convert it to int and store in a new int variable
  myIntValue := int(myFloatValue)
  
  fmt.Println(myIntValue) // Output: 1

This code converts a float value, stored in the variable myFloatValue, to an integer value, stored in a new variable myIntValue. First, we define a float value, myFloatValue, with a value of 1.5.

Then, using the int() function, we convert the value from a float to an integer and store it in a new int variable named myIntValue. Lastly, we print out the new integer value, myIntValue, which will output 1.

go