Go

strconv — String ↔ Number Conversions

admin by @admin ADMIN
3d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`strconv.Atoi` / `Itoa` for the common int<->string case; `ParseFloat`, `ParseBool`, `Quote` for everything else. Always handle the error — strings can be anything.
Go
Raw
package main

import (
    "fmt"
    "strconv"
)

func main() {
    // int <-> string
    n, err := strconv.Atoi("42")
    if err != nil { fmt.Println("not a number:", err) }
    fmt.Println(n)                                // 42
    fmt.Println(strconv.Itoa(7))                  // "7"

    // Floats with controlled precision
    f, _ := strconv.ParseFloat("3.14159", 64)
    fmt.Println(strconv.FormatFloat(f, 'f', 2, 64)) // "3.14"

    // Bools — "1", "t", "TRUE", etc. all work
    b, _ := strconv.ParseBool("true")
    fmt.Println(b)                                // true

    // Quote for safe embedding in source / shell
    fmt.Println(strconv.Quote(`hello "world"`))   // "hello \"world\""

    // Different bases
    i, _ := strconv.ParseInt("ff", 16, 64)
    fmt.Println(i)                                // 255
    fmt.Println(strconv.FormatInt(255, 16))       // "ff"
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.