Count Decimal Places in C++

In this post, we will see how to count decimal places in C++.

Accuracy V/S Precision in Counting Decimal Places in C++ Programs

A major challenge that comes with counting decimal places is that the program can either give a solution that is accurate or precise.

An accurate solution is considered to be closest to the original figure, for example, an accurate rounded-off value for 22/7 can be written as 3.14, whereas a precise solution will have a greater number of decimal places, like 3.142857142….

Similarly, a C++ program can either round off decimal places up to an extent or it can provide a highly precise solution.

How to Count Decimal Places in C++

There can be multiple ways to count number of decimal places in C++. Let’s go through them.

Example 1: Use String Functions to Find Precise Number of Decimal Places

Till now we have seen how to find accurate rounded-off decimal places of numbers in C++, but what if we need to get decimal places of numbers that are highly precise?

This can be achieved by creating a C++ program that uses string functions to count the digits that are positioned after the decimal up to the length of the string.

  1. A string variable num is created that takes user input using the getline function.

    string num;
    getline(cin, num);
    
  2. To find the position of the decimal, an integer variable len is created which finds and stores the index of the decimal using the find_last_of() function.

    int len = num.find_last_of('.');
    
  3. The program erases the decimal and the numbers before it so that only the decimal values are present inside the variable num.

    num.erase(0,len+1);
    

Lastly, the length of the variable num is stored in a new integer variable new_len and it is printed.

#include 
#include 

using namespace std;

int main()
{
    string num;
    cout << "Enter a number to count decimal places = ";
    getline(cin, num);
    int len = num.find_last_of('.');
    num.erase(0,len+1);
    int new_len = num.length();
    cout << "This number has " << new_len << " decimal places" << endl;
}

Output:

Enter a number to count decimal places = 256.2365486
This number has 7 decimal places

Example 2: Count Decimal Places Accurately for a Number

This program counts the decimal places in C++ of any given number that lies under the range of 0 to 10.

  1. The program imports two standard library packages - corecrt_math.h and iostream, and assigns the namespace to std.
  2. Inside the main function, a float variable num is created that stores the given number as input. Another integer variable count is created and initialized with zero. It stores the count of decimal places.
  3. A while loop is created that runs until (num / (int)num != 1. For example, a number like 1.253 when divided by itself would give 1 as quotient, but only when the denominator is free of all the decimals - 1253 / 1 = 1. It is done by typecasting the variable num.
  4. Every time the loop runs, the value of num is multiplied by 10, and the value of count is increased by 1. This way, when the loop terminates, the value of the count gets equal to the number of decimal places of num.
  5. Lastly, the variable count is printed.
#include 
#include 

using namespace std;

int main() {

    float num;     // Number given as input
    cout << "Enter a numer = ";
    cin >> num;
    int count = 0;        // Count of Decimal places
    while (num / (int)num != 1)  // loop runs until num/(int)num is 1
    {
        count += 1;           // Adds 1 to count
        num *= 10;            // num is multipled by 10
    }
    cout << count << " decimal Places"; // Prints the count of decimal places
}

Executing this program gives an output:

Enter a numer = 1.1413
4 decimal Places

Example 3: Create a Program that divides two numbers and returns their decimal places

This program divides two numbers and displays the number of decimal places. The approach this program takes is that it creates an unordered map that stores the remainders.

When the program finds the value of the current remainder already present in the map, it prints a message that the result has infinite decimal places. Otherwise, it prints the number of decimal places.

The program imports iostream and unordered_map library packages.

Method - decimal_places

  1. A method decimal_places is created which has two integer parameters int a and int b.

    int decimal_places(int a, int b)
    
  2. Two new variables are created locally in this method - int count which is responsible to count the number of decimal places in the given number and it is initialized with 0. The second variable is an unordered map count_map, which is a hash table that c++ creates internally.

    int count = 0; // result variable
       unordered_map count_map;
    
  3. A while loop is created that runs until the value of a % b is zero. The modulus of a % b is overwritten on a with each round of loop and the value of count is increased by 1.

  4. Inside the if statement, if the count_map.find(a) is not equal to count_map.end(), it returns -1, which means that the remainders are getting repeated.

  5. A value 1 is provided to the key of count_map using count_map[a] = 1.

  6. The value of a is multiplied by 10.

       while (a % b != 0) {
           a %= b;
           count += 1;
           if (count_map.find(a) != count_map.end()) {
               return -1;
           }
           count_map[a] = 1;
           a *= 10;
       }
    return count;
    }
    
  7. Outside the while loop, the variable count is returned.

Method - print_results

Another method print_results is created which has an integer parameter result and it will be used to display the results.

If the value of result passed from method decimal_places is found as -1, it prints a message of infinite decimal places. Otherwise, the number of decimal places is printed.

void print_result(int result) {
    if (result == -1)
        cout << "Infinite Decimal Places";
    else
        cout << "Resultant has " << result << " Decimal Places";
}

Complete code is given below:

#include 
#include 

using namespace std;

int decimal_places(int a, int b) {
    int count = 0; // result variable
    unordered_map count_map;
    // calculating remainder
    while (a % b != 0) {
        a %= b;
        count += 1;
        if (count_map.find(a) != count_map.end()) {
            return -1;
        }
        count_map[a] = 1;
        a *= 10;
    }
    return count;
}

void print_result(int result) {
    if (result == -1)
        cout << "Infinite Decimal Places";
    else
        cout << "Resultant has " << result << " Decimal Places";
}
int main() {
    int dp = decimal_places(22, 8);
    print_result(dp);
    return 0;
}

Output:

Resultant has 2 Decimal Places

Let's check for the value of Pi - int dp = decimal_places(22, 7);

Infinite Decimal Places

Example 4: Find the Number of Decimal Places Using the Trunc() Function

This program provides a different approach to counting the number of decimal places in C++. At first, the program finds the truncated value of the number that is given as input.

For example, 5.12 when truncated gives 5. Subtracting the truncated number from itself leaves only the decimal places in the number which is 0.12.

Continuously multiplying 0.12 with 10 in a loop, and then subtracting it from its truncated value will reduce the number to 0 at the end. Incrementing a variable for the number of times the loop iterated will accurately count the decimal places in C++ for this number.

Let's look at how to code this logic into a C++ program.

  1. Create three variables inside the main function - int count, double num, and double carry. The count variable is initialized with zero, and the value of num is initialized with a given input.

  2. The truncated value of num is stored inside carry using the syntax:

    double carry = trunc(num);
    
  3. Now, to eliminate the places of tens and ones from the original number, carry is subtracted from the num.

    num = num - carry;
    
  4. A while loop is created which runs until the value of num is reduced to less than 0.0000001.

    The reason to not use num!=0 is because the way the datatype double counts numbers, the loop would keep on running even if the value of num gets to zero, as internally it might be calculated as 0.00000001 by the program.

    while (num >= 0.0000001) {
    
  5. Inside the while loop, the variable num is multiplied by 10, the value of count is incremented by 1 and lastly, the value of num is substracted by its truncated value.

  6. The value of count is printed outside the while loop.

#include 
#include 
using namespace std;

int main()
{
    int count = 0;
    double num = 5.1246549;
    double carry = trunc(num);
    num = num - carry;
    while (num >= 0.0000001) {
        num = num * 10;
        count = count + 1;
        num = num - trunc(num);
    }
    cout << "No. of decimal places are " << count;
}

Output:

No. of decimal places are 7

Conclusion

This program explains various ways to count the number of decimal places in C++. The reader after going through the article will be able to easily create programs that count decimal places of numbers in C++.

Thats all about how to count decimal places in C++.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.