Go:Go Type Conversion and strconv Package (Atoi, Itoa)
Go•Type Conversion

Go Type Conversion and strconv Package (Atoi, Itoa)

Learn explicit type conversions in Go and parsing strings to numbers safely with strconv.

Syntax

val := int(floatVal) num, err := strconv.Atoi("123")

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
strconv.AtoiFunctionASCII to integer conversion returning (int, error).
strconv.ItoaFunctionInteger to ASCII string conversion.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Go locally:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // 1. Primitive conversion
    floatVal := 42.85
    intVal := int(floatVal) // Truncates decimal
    fmt.Printf("Float to int: %d (from %.2f)\n", intVal, floatVal)

    // 2. String to integer parsing with strconv.Atoi
    rawInput := "8080"
    port, err := strconv.Atoi(rawInput)
    if err != nil {
        fmt.Println("Parse Error:", err)
        return
    }
    fmt.Printf("Parsed port:  %d (Port + 1 = %d)\n", port, port+1)
}
Expected Output:
Float to int: 42 (from 42.85)
Parsed port:  8080 (Port + 1 = 8081)

How It Works: Step-by-Step

  • Lines 10-12: Explicit int(floatVal) cast truncates decimal.
  • Lines 15-17: strconv.Atoi converts string to int and returns error check.

Key Concepts

  • In Go, all conversions are explicit: T(v).
  • strconv.Atoi returns both the parsed integer and an error object.

Common Mistake: Using string(int) expecting string representation "65"

In Go, string(65) converts the integer to ASCII character "A", NOT the string "65"!

❌ Incorrect
s := string(65) // Evaluates to "A", not "65"!
✅ Correct
s := strconv.Itoa(65) // Evaluates to "65"

Related Go Tutorials & Compiler

Run and test Go on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Go Online Compiler