Jump to content

Getting the number of decimal places: Difference between revisions

Line 97:
12.345556 has 14 decimals
1234500000000000060751116919315055127939946206157864960.000000 has 0 decimals</pre>
 
=={{header|C++}}==
{{trans|C}}
<lang cpp>#include <iomanip>
#include <iostream>
#include <sstream>
 
int findNumOfDec(double x) {
std::stringstream ss;
ss << std::fixed << std::setprecision(14) << x;
 
auto s = ss.str();
auto pos = s.find('.');
if (pos == std::string::npos) {
return 0;
}
 
auto tail = s.find_last_not_of('0');
 
return tail - pos;
}
 
void test(double x) {
std::cout << x << " has " << findNumOfDec(x) << " decimals\n";
}
 
int main() {
test(12.0);
test(12.345);
test(12.345555555555);
test(12.3450);
test(12.34555555555555555555);
test(1.2345e+54);
return 0;
}</lang>
{{out}}
<pre>12 has 0 decimals
12.345 has 3 decimals
12.3456 has 12 decimals
12.345 has 3 decimals
12.3456 has 14 decimals
1.2345e+54 has 0 decimals</pre>
 
=={{header|Go}}==
1,452

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.