I'm trying to get the first two digits after the decimal point of a number and the check to see if they are equal to each other and, at the same time, not equal to 0.
I know how to do the checking stuff but I have no idea how to select the first two digits after the decimal point .
Using setprecision would give me the number entirely, not just the two digits after the decimal point.
For example:
i = 3.141592
cout << setprecision(3) << i
would output 3.14, but I only want 14 .
You could use the floor function from the std library
int(i*100 - (floor(i))*100)
Here is a good example webpage: http://en.cppreference.com/w/cpp/numeric/math/floor
You could implement a function, that returns the digits as an integer.
#include <math.h>
int digits_after_decimal_point(double number, unsigned int precision){
double trunc = number - static_cast<int>(number); //3,141 > 0,141
return static_cast<int>(trunc * pow(10,precision));
}
Example call:
std::cout << digits_after_decimal_point(3.14159, 3) << std::endl;
Output:
141
But the problem is, checking digits of integers is (without using a bunch of %
operations) pretty undoable. So for checking, you could convert the result into a std::string
(using std::ostringstream
) and than you can compare specific indexes.
You can simply take out the 2 digits after the decimal point by multiplying the number by 100 , and now you have those 2 digits just before the decimal which you can extract by first type-casting the number into integer and then taking mod with 100. for eg : 345.897 is the number multiply by 100 : 34589.7 now typecast to integer : 34589 now mod with 100 : 89 This can be generalized as if the number is x . Last 2 digits are : y = ((int)(x*100))%100; And if you want to get these digits individually to compare again take mod with 10 and divide by 10 twice. for eg : number is now y digit1 = y%10 divide the y by 10 digit2 = y%10 compare digit1 and digit2 as you want
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.