Go: How to Convert Float to Int with Example Code
In Go, convert a float to an int by using simple type conversion like
int(yourFloat), which drops the decimal part and keeps the integer portion.Examples
Input3.14
Output3
Input-7.99
Output-7
Input0.0
Output0
How to Think About It
To convert a float to an int in Go, think of it as taking the number and removing everything after the decimal point. You do this by telling Go to treat the float as an int using
int() conversion, which simply cuts off the decimal part without rounding.Algorithm
1
Get the float value you want to convert.2
Use the <code>int()</code> conversion to change the float to an int.3
Return or use the resulting integer value.Code
go
package main import "fmt" func main() { var f float64 = 3.99 i := int(f) fmt.Println(i) // Output: 3 }
Output
3
Dry Run
Let's trace converting 3.99 to int through the code
1
Start with float
f = 3.99
2
Convert float to int
i = int(f) => i = 3
3
Print result
Output: 3
| Step | Value of f | Value of i | Output |
|---|---|---|---|
| 1 | 3.99 | - | - |
| 2 | 3.99 | 3 | - |
| 3 | 3.99 | 3 | 3 |
Why This Works
Step 1: Type Conversion
Using int() tells Go to convert the float value to an integer type.
Step 2: Decimal Truncation
The conversion drops the decimal part without rounding, so 3.99 becomes 3.
Step 3: Result Usage
The resulting integer can be used wherever an int is needed, like printing or calculations.
Alternative Approaches
Using math.Floor for rounding down
go
package main import ( "fmt" "math" ) func main() { f := 3.99 i := int(math.Floor(f)) fmt.Println(i) // Output: 3 }
This method explicitly rounds down before converting, useful if you want to be clear about rounding behavior.
Using math.Round for nearest integer
go
package main import ( "fmt" "math" ) func main() { f := 3.5 i := int(math.Round(f)) fmt.Println(i) // Output: 4 }
This rounds the float to the nearest integer before converting, unlike simple truncation.
Complexity: O(1) time, O(1) space
Time Complexity
Conversion is a simple, direct operation with no loops, so it runs in constant time.
Space Complexity
No extra memory is needed beyond the variables holding the float and int values.
Which Approach is Fastest?
Simple type conversion int() is fastest; using math.Floor or math.Round adds function call overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| int() conversion | O(1) | O(1) | Fast truncation without rounding |
| math.Floor + int() | O(1) | O(1) | Explicit rounding down |
| math.Round + int() | O(1) | O(1) | Rounding to nearest integer |
Use
int(yourFloat) to quickly convert a float to an int by dropping decimals.Expecting
int() conversion to round the float instead of truncating the decimal part.