Check if a character is a number in Golang

Saturday, December 19, 2020 • 2 minutes to read

Golang2020to-the-pointgolang

Unicode is a computing standard for the consistent encoding symbols.

All the characters and symbols assigned a code.

For ex.

1A U+0041
2 U+0905

All the Unicode is divided into various categories. Browse all the categories.

  • Ll Lowercase Letters (a, b, µ, ɸ)
  • Nl Letter Number (Ⅰ, ᛯ)
  • Lo Other Letter (अ, ƻ)

Golang package unicode provides a wide range of validation methods on different set of Unicode.

IsNumber

IsNumber function validates the set of Unicode number characters, category N(Nd, Nl, No).

Syntax

1func IsNumber(r rune) bool
 1package main
 2
 3import (
 4	"fmt"
 5	"unicode"
 6)
 7
 8func main() {
 9	str := "1b१Ⅰ¼"
10	for _, char := range str {
11		if unicode.IsNumber(char) {
12			fmt.Println(string(char), char, "is number rune")
13		} else {
14			fmt.Println(string(char), char, "is not a number rune")
15		}
16	}
17}

Output

11 49 is number rune
2b 98 is not a number rune
3 2407 is number rune
48544 is number rune
5¼ 188 is number rune

Try it

IsDigit

IsDigit function validates only the Nd Unicode category. It is a subset of IsNumber.

Syntax

1func IsDigit(r rune) bool
 1package main
 2
 3import (
 4	"fmt"
 5	"unicode"
 6)
 7
 8func main() {
 9	str := "1b१Ⅰ¼"
10
11	for _, char := range str {
12		if unicode.IsDigit(char) {
13			fmt.Println(string(char), char, "is digit rune")
14		} else {
15			fmt.Println(string(char), char, "is not a digit rune")
16		}
17	}
18}

Output

11 49 is digit rune
2b 98 is not a digit rune
3 2407 is digit rune
48544 is not a digit rune
5¼ 188 is not a digit rune

Final Words

You can always use a validation on ASCII values. ASCII value of 0 is 30 and 9 is 39.
If >= 30 and <= 39.


Golang2020to-the-pointgolang

PreviousGolang String Replace

NextConvert Hexadecimal to Decimal and Decimal to Hexadecimal in Golang