Skip to Content
Course content

115: strconv.Itoa, Atoi, ParseFloat, FormatInt

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're working at a shipping warehouse. Everything arriving on the conveyor belt is wrapped in a generic plastic sleeve—that's your string. To the warehouse system, everything in a sleeve is just "text." But if the sleeve contains a number representing the weight of a package, you can't actually do any math with it while it's still in the plastic. You have to "unwrap" it into a number to add it to a total. Conversely, when you want to print a shipping label, you have to take that raw number and "wrap" it back into text so the printer can understand it.

In Go, the strconv package is your wrapping and unwrapping station. Here is how that maps to the code:

  • Unwrapping text into an integer: That's strconv.Atoi (ASCII to Integer).
  • Wrapping an integer into text: That's strconv.Itoa (Integer to ASCII).
  • Unwrapping text into a decimal: That's strconv.ParseFloat.
  • Custom wrapping: That's strconv.FormatInt, which lets you decide if you want the number to look like a normal decimal, a binary string, or a hex code.

Quick Swaps with Atoi and Itoa

If you're just dealing with basic int types, Atoi and Itoa are your best friends because they are shorthand. I use these 90% of the time when I'm just trying to get a number from a CLI argument or a simple API response.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // Wrapping: int -> string
    age := 25
    ageStr := strconv.Itoa(age)
    fmt.Printf("The age is now a string: %s\n", ageStr)

    // Unwrapping: string -> int
    input := "42"
    val, err := strconv.Atoi(input)
    if err != nil {
        fmt.Println("That wasn't a number!")
        return
    }
    fmt.Printf("The value is now an int: %d\n", val)
}

Notice that Atoi returns two values. This is where beginners often trip up. Since the string "hello" cannot be converted to an integer, Go forces you to handle that error. Don't ignore it with an underscore unless you're absolutely certain the input is sanitized.

Dealing with Decimals

Atoi only works for whole numbers. If you're dealing with prices, coordinates, or percentages, you need ParseFloat. Unlike Atoi, ParseFloat requires two arguments: the string and the "bit size" (usually 32 or 64).

priceStr := "19.99"
price, err := strconv.ParseFloat(priceStr, 64)
if err != nil {
    fmt.Println("Invalid price format")
}
fmt.Printf("Price as float: %.2f\n", price)

I almost always use 64 because float64 is the standard for most math in Go. If you use 32, you're just asking for precision headaches later on.

Going Beyond Base 10

Sometimes Itoa isn't enough. What if you're writing a tool that needs to display a memory address in Hexadecimal or a permission bitmask in Binary? That's where FormatInt comes in. It takes an int64 and a base (2 to 36).

var num int64 = 255

// Base 10 (Same as Itoa, but for int64)
fmt.Println(strconv.FormatInt(num, 10)) // "255"

// Base 16 (Hexadecimal)
fmt.Println(strconv.FormatInt(num, 16)) // "ff"

// Base 2 (Binary)
fmt.Println(strconv.FormatInt(num, 2))  // "11111111"

One quick tip: FormatInt explicitly requires an int64. If you have a standard int, you'll need to cast it: strconv.FormatInt(int64(myInt), 16). It's a bit wordy, but it keeps the type system strict.




📋 Practical Task

Building a CSV-style Budget Parser

You are building a small tool that reads a simulated CSV line representing a purchase. The input is a single string where the item name, quantity, and unit price are separated by commas. Your task is to parse this string and calculate the total cost.

Requirements:

  • Start with this input string: "Widget,5,12.50"
  • Use strings.Split to break the string into a slice.
  • Convert the quantity (index 1) from a string to an integer using strconv.Atoi.
  • Convert the price (index 2) from a string to a float using strconv.ParseFloat.
  • Calculate the total (quantity * price).
  • Print the final result in this exact format: "Total cost for Widget: 62.50" (where the number is a float).
  • Ensure you handle errors for both conversions; if a conversion fails, print "Invalid input data" and stop.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.