GO Program to count digits in a number

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

How to count digits in a number

Let us have basic logic for find the number of digits in a given number.

Assign the number whose digits have to be count to a variable X. Assign another variabble Y to hold the count of the given number. Divide the number (X) by 10 until the number is greater than 0 and for each iteration increment the value of Y. At the end of the program Y will return the count of digits of the given number.


How to count digits in a number in the Go Program

We are using fmt.println() function for printing the string to the output screen. Here we are showing how to count digits in a number in the Go language. Here variables numberholding the number whose digits have to be count, and variable Cnt for holding the count. The digits are calculated as number=number/10 in a for-loop. Given below are the steps which are used in the Go program. 


STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the variable number, Cnt 

STEP 4: Initialise integer variable Cnt=0

STEP 5: Read the number number using fmt.Scanln()

STEP 6: Use for loop for count the digits as number=number/10 and Cnt=Cnt+1

STEP 7: Print the count Cnt using fmt.Println()


GO Source Code

                                          package main
import "fmt"

func main() {
    var number, Cnt int
    Cnt = 0
    fmt.Print("Enter any number for digits count = ")
    fmt.Scanln(& number)

    for number > 0 {
        number= number/ 10
        Cnt = Cnt + 1
    fmt.Println("The number of digits = ", Cnt)


Enter any number for digits count = 4986

The number of digits = 4