Parse Numbers in Go (Challenge)

GoGoBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

The purpose of this challenge is to demonstrate how to parse numbers from strings in Go.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/AdvancedTopicsGroup(["`Advanced Topics`"]) go/AdvancedTopicsGroup -.-> go/number_parsing("`Number Parsing`") subgraph Lab Skills go/number_parsing -.-> lab-15412{{"`Parse Numbers in Go (Challenge)`"}} end

Number Parsing

Parsing numbers from strings is a common task in many programs. This challenge requires you to use the built-in strconv package to parse different types of numbers from strings.

Requirements

  • Use the strconv package to parse numbers from strings.
  • Parse a float with ParseFloat.
  • Parse an int with ParseInt.
  • Parse a hex-formatted number with ParseInt.
  • Parse an unsigned int with ParseUint.
  • Parse a base-10 int with Atoi.
  • Handle errors returned by the parse functions.

Example

$ go run number-parsing.go
1.234
123
456
789
135
strconv.ParseInt: parsing "wat": invalid syntax

## Next we'll look at another common parsing task: URLs.

Summary

This challenge demonstrated how to parse different types of numbers from strings in Go using the strconv package. By completing this challenge, you should have a better understanding of how to handle number parsing in your Go programs.

Other Go Tutorials you may like