How to check if a string is a number in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To check string is a number, golang provides the strconv.Atoi() function just pass your string if it’s a number string then it will convert into a number else throw an error.

Today, I’m going to show you how do you check if a string is a number in golang, as above mentioned I’m going to use the strconv.Atoi() method to validate string is a number or not.

Let’s start today’s tutorial How do I check if a string is a number in golang?

Here, we will take two examples first is a valid number string and the second is an invalid number string so we are able to understand strconv.Atoi() working properly or not.

let’s write a code.

package main

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

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

Above program will print which number string is valid number and which is not, let’s check the output.

check, string is a number, golang

Try it yourself

All the best 👍

Follow me on Twitter