Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
115: strconv.Itoa, Atoi, ParseFloat, FormatInt
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.Splitto 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.
There are no comments for now.