How to Convert Float to Int in Go

You convert a float to an int in Go using an explicit type conversion, such as `int(floatValue)`, which truncates the decimal part toward zero.

You convert a float to an int in Go using an explicit type conversion, such as int(floatValue), which truncates the decimal part toward zero. This operation does not round the number; it simply drops everything after the decimal point.

Because Go does not allow implicit conversions between numeric types, you must always cast explicitly. Be aware that if the float value is too large to fit in an int (e.g., math.MaxFloat64), the conversion will wrap around or produce undefined behavior depending on the architecture, so you should validate the range if the input is untrusted. If you need rounding instead of truncation, use the math package functions like math.Round, math.Floor, or math.Ceil before casting.

Here are two practical examples showing truncation and rounding:

package main

import (
	"fmt"
	"math"
)

func main() {
	// Truncation: drops decimals toward zero
	var f1 float64 = 99.99
	i1 := int(f1)
	fmt.Printf("Truncated: %d\n", i1) // Output: 99

	// Rounding: rounds to nearest integer before casting
	var f2 float64 = 99.5
	i2 := int(math.Round(f2))
	fmt.Printf("Rounded: %d\n", i2)   // Output: 100

	// Negative numbers: truncation moves toward zero
	var f3 float64 = -45.8
	i3 := int(f3)
	fmt.Printf("Negative truncated: %d\n", i3) // Output: -45
}

If you are working with command-line tools or shell scripts that invoke Go, you might need to handle this conversion within a binary or a script. For instance, if you are piping data into a Go program that expects integers, ensure your parsing logic handles the float-to-int conversion explicitly to avoid runtime panics or logic errors.

# Example: Running a Go binary that expects float input but processes it as int
echo "123.45" | go run main.go
# Inside main.go, you would parse the float and convert:
# val, _ := strconv.ParseFloat(input, 64)
# intVal := int(val)

Always remember that int size depends on the system architecture (32-bit vs 64-bit), so if you need a specific width, use int32 or int64 instead of the generic int.