Sling Academy
Home/Golang/Converting Numbers to and from Strings in Go

Converting Numbers to and from Strings in Go

Last updated: November 24, 2024

Working with numbers and strings in Go is a common task, especially when dealing with data input and output that requires conversion between these types. In this article, we will explore how to convert numbers to strings and vice versa in Go. Let's dive into some examples!

1. Converting Numbers to Strings

In Go, you can convert numbers to strings using the strconv package, which provides various functions for string conversions.

1.1 Basic Conversion

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // Convert an int to a string
    myInt := 123
    myString := strconv.Itoa(myInt)
    fmt.Println("Int to String:", myString)

    // Convert a float to a string
    myFloat := 123.45
    myStringFloat := strconv.FormatFloat(myFloat, 'f', -1, 64)
    fmt.Println("Float to String:", myStringFloat)
}

1.2 Intermediate Conversion with Formatting

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // Convert and format a float to a string with 2 decimal points
    myFloat := 123.456
    myString := strconv.FormatFloat(myFloat, 'f', 2, 64)
    fmt.Printf("Formatted Float to String: %s\n", myString)
}

2. Converting Strings to Numbers

Similar to number to string conversion, the strconv package also facilitates converting strings to numbers.

2.1 Basic Conversion

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // Convert a string to an int
    myString := "456"
    myInt, err := strconv.Atoi(myString)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("String to Int:", myInt)

    // Convert a string to a float
    myStringFloat := "456.78"
    myFloat, err := strconv.ParseFloat(myStringFloat, 64)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("String to Float:", myFloat)
}

2.2 Advanced Conversion with Error Handling

package main

import (
    "fmt"
    "strconv"
)

func convertStringToInt(s string) (int, error) {
    return strconv.Atoi(s)
}

func convertStringToFloat(s string) (float64, error) {
    return strconv.ParseFloat(s, 64)
}

func main() {
    myStrings := []string{"abc", "123", "100.5f"}

    for _, str := range myStrings {
        // Attempt to convert each string to int
        if num, err := convertStringToInt(str); err == nil {
            fmt.Println("Converted Int:", num)
        } else {
            fmt.Printf("Failed to convert '%s' to Int: %s\n", str, err)
        }

        // Attempt to convert each string to float
        if num, err := convertStringToFloat(str); err == nil {
            fmt.Println("Converted Float:", num)
        } else {
            fmt.Printf("Failed to convert '%s' to Float: %s\n", str, err)
        }
    }
}

In the provided examples, we demonstrated various methods of converting between strings and numbers, incorporating basic, intermediate, and advanced methods with formatting and error handling.

Understanding how these conversions work and effectively utilizing the strconv package is key when processing string representations of numerical data in Go. Happy coding!

Next Article: Exploring Scientific Notation for Floating Points in Go

Previous Article: Understanding Binary, Octal, and Hexadecimal Numbers in Go

Series: Numbers and Math 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