Is there any way to determine how many numbers are there in my double after decimal point. for example double a=3.14259
If I make a new int b
now, how can I make value of b
equal to numbers after decimal point from a
?
Is there any way to determine how many numbers are there in my double after decimal point. for example double a=3.14259
If I make a new int b
now, how can I make value of b
equal to numbers after decimal point from a
?
The short answer is, you can't.
first of all, a type like double
has always the same number of binary digits after a (binary) period. That is called mantissa. in case of double that are 53 bits, meaning 52 bit after binary period, in decimal that are about 15 digits. For details you may have a look a IEEE_754 (double precision)
When you convert a double to a decimal string, you will in general never match exact decimal. For example the value 0.1
could not exactly represented by a double value. a printf may show "0.1" after applying rounding.
However, when you are dealing with some double calculations you will experience small deriviation like 0.10000000000012
or 0.09999999999987
. What will you do in such cases?
And there is a mathematican problem which has nothing to do with c++ doubles:
_
0.1 is equal to 0.09
so your answer would either 1 or infinity
Here is one way to do it: Convert the decimal to a string, and find the size of the substring after the decimal point, as follows:
#include <iostream>
#include <string>
int main()
{
double a = 3.14259;
std::string a_string = std::to_string(a);
a_string.erase ( a_string.find_last_not_of('0') + 1, std::string::npos ); //Get rid
//of extra zeroes
std::cout << a_string.substr(a_string.find('.') + 1).size() << "\n";
//Print the size of the substring of the original string from the decimal point (here 5)
}
You could treat the fractional part as a string literal. Utilize the std::stringstream and std::string:
#include <iostream>
#include <string>
#include <sstream>
int main(){
double whole = 3.14259;
auto fractionalno = whole - static_cast<long>(whole); // or use std::modf()
std::stringstream ss;
ss << fractionalno;
std::string s = ss.str();
s.erase(0,2);
std::cout << "The number of digits is: " << s.size();
}
Floating point number does not provide the number of digits after the point. (It is not even the 'exact' value. It is an approximate value.)
But if you just want to make another integer to have the same number of digits after the point just on the screen, why don't you just count?
Here is Python code:
a = 4.0 / 7
# a is 0.5714285714285714
b = str(a)
# b (str(a)) is 0.571428571429, different with a.
nod = len(b[b.index('.'):])
_c = 9.0 / 7
c = float(int(_c * 10 ** nod)) / 10 ** nod