IsNumber()
functionThe 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.
func IsNumber(r rune) bool
r
: This is the rune
type value that we are checking whether it is a numerical character or not.
The function itself is of type bool
.
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"
)
The following code shows how to use the IsNumber()
function in Golang.
// Golang program// using unicode.IsNumber() Functionpackage mainimport ("fmt""unicode")func main() {// checks if the char is a number or not// returns true if it is a number. Otherwis, falsefmt.Println("The unicode.IsNumber('ⅱ')",unicode.IsNumber('ⅱ'))fmt.Println("The unicode.IsNumber('B'):",unicode.IsNumber('B'))fmt.Println("The unicode.IsNumber('Ⅻ'):",unicode.IsNumber('Ⅻ'))}
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() Functionpackage mainimport ("fmt""unicode")func main() {// declaring a variable mystrmyStr := "ⅠS¼+4Bag"// a for loop to iterate the variable myStrfor _, char := range myStr {// the if statement checks if each character passed is a number// The displayed result depends on the return valueif unicode.IsNumber(char) {fmt.Println(string(char), char, "is number rune")} else {fmt.Println(string(char), char, "is not a number rune")}}}