0PricingLogin
Go Academy · Lesson

strconv, math and sort

Type conversion, math utilities, and sorting

strconv: String Conversions

The strconv package converts between strings and basic types:

package main
import ("fmt"; "strconv")

func main() {
    // String to int
    n, err := strconv.Atoi("42")
    fmt.Println(n, err)           // 42 <nil>

    // Int to string
    s := strconv.Itoa(123)
    fmt.Println(s)                // "123"

    // String to float64
    f, _ := strconv.ParseFloat("3.14", 64)
    fmt.Println(f)                // 3.14

    // Float64 to string
    fs := strconv.FormatFloat(f, 'f', 2, 64)
    fmt.Println(fs)               // "3.14"
}

strconv.ParseInt and ParseBool

Parse integers with base and bool values:

package main
import ("fmt"; "strconv")

func main() {
    // Parse int with base
    n, _ := strconv.ParseInt("FF", 16, 64)   // hex
    fmt.Println(n)  // 255

    n2, _ := strconv.ParseInt("11111111", 2, 64) // binary
    fmt.Println(n2) // 255

    // Bool parsing
    b1, _ := strconv.ParseBool("true")
    b2, _ := strconv.ParseBool("1")
    b3, _ := strconv.ParseBool("T")
    fmt.Println(b1, b2, b3) // true true true
}

All lessons in this course

  1. fmt and strings Packages
  2. strconv, math and sort
  3. time Package Essentials
  4. os and filepath Packages
← Back to Go Academy