Check If the Rune is a Decimal Digit or not in Golang


A rune is a Unicode code point that is used as an alias for the int32 type in Go. It is frequently employed to denote a single character within a string. We occasionally need to determine whether a rune represents a decimal digit. This article will cover how to determine in Go whether a rune is a decimal digit.

Using the unicode.IsDigit() Function

To work with Unicode code points, Go has the unicode package, which includes functions. To determine whether a particular rune is a decimal digit or not, use the IsDigit() function of this package.

A rune can be passed as an argument to the IsDigit() function, which returns a boolean value indicating if the rune is a decimal digit. As an example βˆ’

Example

package main

import (
   "fmt"
   "unicode"
)

func main() {
   r := '9'
   if unicode.IsDigit(r) {
      fmt.Printf("%c is a decimal digit\n", r)
   } else {
      fmt.Printf("%c is not a decimal digit\n", r)
   }
}

In this example, we have used the IsDigit() function to check if the rune '9' is a decimal digit or not. The IsDigit() function returns true in this case, so the output will be βˆ’

Output

9 is a decimal digit

Similarly, we can check if other runes are decimal digits using the IsDigit() function.

Converting a Rune to a String and Checking

If we have a rune that we want to check if it is a decimal digit, we can convert it to a string and check if the string contains only digits. We can use the strconv.Itoa() function to convert the rune to a string and the strings.ContainsAny() function to check if the string contains only digits.

Example

package main

import (
   "fmt"
   "strconv"
   "strings"
)

func main() {
   r := '5'
   s := strconv.Itoa(int(r))
   if strings.ContainsAny(s, "0123456789") {
      fmt.Printf("%c is a decimal digit\n", r)
   } else {
      fmt.Printf("%c is not a decimal digit\n", r)
   }
}

In this example, we have converted the rune '5' to a string using the strconv.Itoa() function. Then, we have used the strings.ContainsAny() function to check if the string contains only digits. The ContainsAny() function returns true if the string contains any of the specified characters, which in this case are the digits from 0 to 9. Since '5' is a decimal digit, the output will be βˆ’

Output

5 is a decimal digit

Conclusion

In Go, we can use the unicode.IsDigit() function to check if a given rune is a decimal digit. We can also convert a rune to a string and check if the string contains only digits using the strconv.Itoa() and strings.ContainsAny() functions. Knowing how to check if a rune is a decimal digit can be useful when working with text and parsing data in Go.

Updated on: 07-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements