What is the Unicode.IsNumber() function in Golang?

The Golang IsNumber() function

The IsNumber() function in the Unicode package is used to determine whether a given element r is of datatype rune, that is, a numerical value. It checks if a set of Unicode number characters in category N is valid.

Syntax

func IsNumber(r rune) bool

Parameter

r: This is the rune type value that we are checking whether it is a numerical character or not.

Return type

The function itself is of type bool.

Return value

The IsNumber() function returns true if rune r is a numerical character. Otherwise, it returns false.

We must import the Unicode package into our program.

package main
  
import (
    "fmt"
    "unicode"
)

Code

The following code shows how to use the IsNumber() function in Golang.

// Golang program
// using unicode.IsNumber() Function
package main
import (
"fmt"
"unicode"
)
func main() {
// checks if the char is a number or not
// returns true if it is a number. Otherwis, false
fmt.Println("The unicode.IsNumber('ⅱ')",
unicode.IsNumber('ⅱ'))
fmt.Println("The unicode.IsNumber('B'):",
unicode.IsNumber('B'))
fmt.Println("The unicode.IsNumber('Ⅻ'):",
unicode.IsNumber('Ⅻ'))
}
What if we have a string of characters to check?

Code explanation

  • Line 4: We add the package main.

  • Lines 6-9: We import the necessary packages in Golang project.

  • Lines 11-21: We define the main() and the unicode.IsNumber() functions, and print the results.

The following example shows how to read a string of characters using the for loop and IsNumber() function.

// Golang program
// using unicode.IsNumber() Function
package main
import (
"fmt"
"unicode"
)
func main() {
// declaring a variable mystr
myStr := "ⅠS¼+4Bag"
// a for loop to iterate the variable myStr
for _, char := range myStr {
// the if statement checks if each character passed is a number
// The displayed result depends on the return value
if unicode.IsNumber(char) {
fmt.Println(string(char), char, "is number rune")
} else {
fmt.Println(string(char), char, "is not a number rune")
}
}
}

Free Resources