Table of Contents
- Accuracy V/S Precision in Counting Decimal Places in C++ Programs
- How to Count Decimal Places in C++
- Conclusion
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.
-
A string variable
numis created that takes user input using thegetlinefunction.1234string num;getline(cin, num); -
To find the position of the decimal, an integer variable
lenis created which finds and stores the index of the decimal using thefind_last_of()function.123int len = num.find_last_of('.'); -
The program erases the decimal and the numbers before it so that only the decimal values are present inside the variable
num.123num.erase(0,len+1);
Lastly, the length of the variable num is stored in a new integer variable new_len and it is printed.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> 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:
|
1 2 3 4 |
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.
- The program imports two standard library packages –
corecrt_math.handiostream, and assigns the namespace tostd. - Inside the main function, a float variable
numis created that stores the given number as input. Another integer variablecountis created and initialized with zero. It stores the count of decimal places. - A while loop is created that runs until
(num / (int)num != 1. For example, a number like 1.253 when divided by itself would give1as quotient, but only when the denominator is free of all the decimals –1253 / 1 = 1. It is done by typecasting the variablenum. - Every time the loop runs, the value of
numis multiplied by 10, and the value ofcountis increased by 1. This way, when the loop terminates, the value of the count gets equal to the number of decimal places ofnum. - Lastly, the variable
countis printed.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <corecrt_math.h> #include <iostream> 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:
|
1 2 3 4 |
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
-
A method
decimal_placesis created which has two integer parametersint aandint b.123int decimal_places(int a, int b) -
Two new variables are created locally in this method –
int countwhich 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 mapcount_map, which is a hash table that c++ creates internally.1234int count = 0; // result variableunordered_map count_map; -
A while loop is created that runs until the value of
a % bis zero. The modulus ofa % bis overwritten onawith each round of loop and the value ofcountis increased by 1. -
Inside the if statement, if the
count_map.find(a)is not equal tocount_map.end(), it returns-1, which means that the remainders are getting repeated. -
A value
1is provided to the key ofcount_mapusingcount_map[a] = 1. -
The value of
ais multiplied by10.12345678910111213while (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;} -
Outside the while loop, the variable
countis 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.
|
1 2 3 4 5 6 7 8 |
void print_result(int result) { if (result == -1) cout << "Infinite Decimal Places"; else cout << "Resultant has " << result << " Decimal Places"; } |
Complete code is given below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include <iostream> #include <unordered_map> using namespace std; int decimal_places(int a, int b) { int count = 0; // result variable unordered_map<int, int> 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:
|
1 2 3 |
Resultant has 2 Decimal Places |
Let’s check for the value of Pi – int dp = decimal_places(22, 7);
|
1 2 3 |
Infinite Decimal Places |
Further reading:
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.
-
Create three variables inside the main function –
int count,double num, anddouble carry. Thecountvariable is initialized with zero, and the value ofnumis initialized with a given input. -
The truncated value of
numis stored insidecarryusing the syntax:123double carry = trunc(num); -
Now, to eliminate the places of tens and ones from the original number,
carryis subtracted from thenum.123num = num - carry; -
A while loop is created which runs until the value of
numis reduced to less than 0.0000001.The reason to not use
num!=0is because the way the datatype double counts numbers, the loop would keep on running even if the value ofnumgets to zero, as internally it might be calculated as 0.00000001 by the program.123while (num >= 0.0000001) { -
Inside the while loop, the variable
numis multiplied by 10, the value ofcountis incremented by 1 and lastly, the value ofnumis substracted by its truncated value. -
The value of
countis printed outside the while loop.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <math.h> 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:
|
1 2 3 |
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++.