Sling Academy
Home/Golang/Using the `strconv` Package to Convert Between Strings and Other Types

Using the `strconv` Package to Convert Between Strings and Other Types

Last updated: November 26, 2024

The strconv package in Go provides functions to convert between strings and other data types, such as integers, floats, and booleans. This article will delve into using the strconv package for various conversions with examples.

Converting Strings to Integers

You can convert a string to an integer using the strconv.Atoi function. The input must be a valid integer string, or it will return an error.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := "123"
    num, err := strconv.Atoi(str)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Converted Number:", num)
    }
}

Converting Integers to Strings

To convert an integer to a string, use strconv.Itoa. This is a straightforward conversion.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    num := 123
    str := strconv.Itoa(num)
    fmt.Println("Converted String:", str)
}

Parsing and Formatting Floats

For float to string conversion, use strconv.FormatFloat, specifying the precision and format.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    f := 123.456
    str := strconv.FormatFloat(f, 'f', 2, 64)
    fmt.Println("Formatted String:", str)
}

To convert a string back to a float, use strconv.ParseFloat:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := "123.456"
    f, err := strconv.ParseFloat(str, 64)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Parsed Float:", f)
    }
}

Working with Booleans

Convert a boolean to a string using strconv.FormatBool, and from a string back to a boolean using strconv.ParseBool.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // Format boolean to string
    b := true
    str := strconv.FormatBool(b)
    fmt.Println("Formatted String:", str)

    // Parse string to boolean
    strBool := "true"
    parsedBool, err := strconv.ParseBool(strBool)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Parsed Boolean:", parsedBool)
    }
}

Practical Usage and Error Handling

When using strconv for conversions, always handle potential errors especially when parsing strings that might not correctly convert to the desired type. The error messages provided by these functions can help diagnose issues quickly.

Next Article: Manipulating Strings with the `strings` Package in Go

Previous Article: Understanding the `time` Package for Date and Time Manipulation in Go

Series: Working with Core package in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant