Count the Number of Digits present in a Number in Go



In this tutorial, we will learn how to count the number of digits present in a number in Go. We will cover the basic concept of number manipulation and implement a function to perform the counting.


What is Number Manipulation

Number manipulation involves performing operations on numbers to achieve a specific result. Counting the number of digits in a number is a common task in number manipulation.


Syntax

The syntax to count the number of digits in a number in Go is:

func countDigits(n int) int {
    count := 0
    if n == 0 {
        return 1
    }
    for n != 0 {
        n /= 10
        count++
    }
    return count
}


Example 1: Counting the number of digits in a number

We can create a function to count the number of digits in a given number by repeatedly dividing it by 10 and keeping a count of the iterations.

For example,

  1. Define a function named countDigits that takes one parameter n of type int.
  2. Initialize a variable count to 0 to store the count of digits.
  3. Check if n is 0. If true, return 1.
  4. Use a for loop to iterate while n is not 0.
  5. In each iteration, divide n by 10 and increment the count variable.
  6. Return the count variable.
  7. In the main function, call the countDigits function with a sample number and print the result.

Go Program

package main

import (
    "fmt"
)

func countDigits(n int) int {
    count := 0
    if n == 0 {
        return 1
    }
    for n != 0 {
        n /= 10
        count++
    }
    return count
}

func main() {
    // Sample number
    number := 12345

    // Count the number of digits
    result := countDigits(number)

    // Print the result
    fmt.Printf("Number of digits in %d is %d\n", number, result)
}

Output

Number of digits in 12345 is 5