Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Check if a string is a number in Go (Golang)

Posted on February 23, 2023February 23, 2023 by admin

strconv.Atoi() function can be used to check if the string is a number. If this function returns an error if the passed string is not a number. This function parses the number to base 10

https://golang.org/pkg/strconv/#Atoi

Signature of the function is

func Atoi(s string) (int, error)

Working Code:

package main
import (
"fmt"
"strconv"
)
func main() {
x := "1234"
val, err := strconv.Atoi(x)
if err != nil {
fmt.Printf("Supplied value %s is not a number\n", x)
} else {
fmt.Printf("Supplied value %s is a number with value %d\n", x, val)
}
y := "123b"
val, err = strconv.Atoi(y)
if err != nil {
fmt.Printf("Supplied value %s is not a number\n", y)
} else {
fmt.Printf("Supplied value %s is a number with value %d\n", y, val)
}
}

Output:

Supplied value 1234 is a number with value 1234
Supplied value 123b is not a number
  • go
  • golang
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP