How to output an interger which is calculated to two decimal places? - c++

It is easy to output a double value which is calculated to two decimal places.
And the code snippet is below:
cout.setf(ios_base::showpoint);
cout.setf(ios_base::fixed, ios_base::floatfield);
cout.precision(2);
cout << 10000000.2 << endl; // output: 10000000.20
cout << 2.561452 << endl; // output: 2.56
cout << 24 << endl; // output: 24 but I want 24.00, how to change my code?
How to output an interger which is calculated to two decimal places? I want 24.00 as an output.

It depends on what your 24 is.
If it is a hard-coded value, you can just write:
std::cout << 24.00 << std::endl;
If it's an integer variable, write this:
std::cout << static_cast<double>(myIntegerVariable) << std::endl;
Don't use any of the suggested approaches like adding ".00" as this will break your code if you want to change the precision later.

A rewrite of completeness, please try with following
#include <iostream>
#include <iomanip>
int main()
{
int i = 24;
std::cout << std::fixed << std::setprecision(2) << double(i) << std::endl;
// Output: 24.00
}

Related

A loss of precision

If I have a double string which is equal to "123.546123" and convert it to a double with atof, I get only 123.546. What can I do to fix this?
Here is my code:
#include <iostream>
int main(){
std::string a = "123.546123";
double b = atof(a.c_str());
std::cout << a << std::endl;
std::cout << b << std::endl;
return EXIT_SUCCESS;
}
std::cout prints floating-point values with a precision of 6 by default. To increase that precision, use std::setprecision from <iomanip>, e.g.:
std::cout << std::setprecision(9) << b << std::endl;

fmod telling me fractional part of 1 is 1

I'm trying to check if a double variable p is approximately equal to an integer. At some point in my code I have
double ip;
cout << setprecision(15) << abs(p) << " " << modf(abs(p), &ip) << endl;
And for a given run I get the printout
1 1
This seems to say that the fractional part of 1 is 1, am I missing something here or could there be some roundoff problem etc?
Note: I'm not including the whole code since the origin of p is complicated and I'm just asking if this is a familiar issue
could there be some roundoff problem etc?
There certainly could. If the value is very slightly less than 1, then both its value and its fractional part could be rounded to 1 when displayed.
the origin of p is complicated
Then it's very likely not to be an exact round number.
You are testing a nearly-1-value, so precision of 15 is not enough to describe it unambiguously.
This code shows your problem clearly:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>
using namespace std;
int main() {
double ip, d = nextafter(1., .0); // Get a double just smaller than 1
const auto mp = std::numeric_limits<double>::max_digits10;
cout << 15 << ": " << setprecision(15)
<< abs(d) << " " << modf(abs(d), &ip) << '\n';
cout << mp << ": " << setprecision(mp)
<< abs(d) << " " << modf(abs(d), &ip) << '\n';
}
On coliru: http://coliru.stacked-crooked.com/a/e00ded79c1727299
15: 1 1
17: 0.99999999999999989 0.99999999999999989

C++ can setw and setfill pad the end of a string?

Is there a way to make setw and setfill pad the end of a string instead of the front?
I have a situation where I'm printing something like this.
CONSTANT TEXT variablesizeName1 .....:number1
CONSTANT TEXT varsizeName2 ..........:number2
I want to add a variable amount of '.' to the end of
"CONSTANT TEXT variablesizeName#" so I can make ":number#" line up on the screen.
Note: I have an array of "variablesizeName#" so I know the widest case.
Or
Should I do it manually by setting setw like this
for( int x= 0; x < ARRAYSIZE; x++)
{
string temp = string("CONSTANT TEXT ")+variabletext[x];
cout << temp;
cout << setw(MAXWIDTH - temp.length) << setfill('.') <<":";
cout << Number<<"\n";
}
I guess this would do the job but it feels kind of clunky.
Ideas?
You can use manipulators std::left, std::right, and std::internal to choose where the fill characters go.
For your specific case, something like this could do:
#include <iostream>
#include <iomanip>
#include <string>
const char* C_TEXT = "Constant text ";
const size_t MAXWIDTH = 10;
void print(const std::string& var_text, int num)
{
std::cout << C_TEXT
// align output to left, fill goes to right
<< std::left << std::setw(MAXWIDTH) << std::setfill('.')
<< var_text << ": " << num << '\n';
}
int main()
{
print("1234567890", 42);
print("12345", 101);
}
Output:
Constant text 1234567890: 42
Constant text 12345.....: 101
EDIT:
As mentioned in the link, std::internal works only with integer, floating point and monetary output. For example with negative integers, it'll insert fill characters between negative sign and left-most digit.
This:
int32_t i = -1;
std::cout << std::internal
<< std::setfill('0')
<< std::setw(11) // max 10 digits + negative sign
<< i << '\n';
i = -123;
std::cout << std::internal
<< std::setfill('0')
<< std::setw(11)
<< i;
will output
-0000000001
-0000000123
Something like:
cout << left << setw(MAXWIDTH) << setfill('.') << temp << ':' << Number << endl;
Produces something like:
derp..........................:234
herpderpborp..................:12345678
#include <iostream>
#include <iomanip>
int main()
{
std::cout
<< std::setiosflags(std::ios::left) // left align this section
<< std::setw(30) // within a max of 30 characters
<< std::setfill('.') // fill with .
<< "Hello World!"
<< "\n";
}
//Output:
Hello World!..................

How to output with 3 digits after the decimal point with C++ stream?

Given a variable of float type, how to output it with 3 digits after the decimal point, using iostream in C++?
Use setf and precision.
#include <iostream>
using namespace std;
int main () {
double f = 3.14159;
cout.setf(ios::fixed,ios::floatfield);
cout.precision(3);
cout << f << endl;
return 0;
}
This prints 3.142
This one does show "13.142"
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
double f = 13.14159;
cout << fixed;
cout << setprecision(3) << f << endl;
return 0;
}
You can get fixed number of fractional digits (and many other things) by using the iomanip header. For example:
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.141592653589;
std::cout << std::fixed << std::setprecision(2) << pi << '\n';
return 0;
}
will output:
3.14
Note that both fixed and setprecision change the stream permanently so, if you want to localise the effects, you can save the information beforehand and restore it afterwards:
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.141592653589;
std::cout << pi << '\n';
// Save flags/precision.
std::ios_base::fmtflags oldflags = std::cout.flags();
std::streamsize oldprecision = std::cout.precision();
std::cout << std::fixed << std::setprecision(2) << pi << '\n';
std::cout << pi << '\n';
// Restore flags/precision.
std::cout.flags (oldflags);
std::cout.precision (oldprecision);
std::cout << pi << '\n';
return 0;
}
The output of that is:
3.14159
3.14
3.14
3.14159
If you want to print numbers with precision of 3 digits after decimal, just add the following thing before printing the number cout << std::setprecision(3) << desired_number. Don't forget to add #include <iomanip> in your code.
In general, precision is the maximum number of digits displayed. The manipulator fixed will set up the output stream for displaying values in fixed format. In fixed the precision is the number of digits after the decimal point. The setprecision allows setting the precision used for displaying floating-point values, it takes an integer argument.
cout << fixed;
cout << setprecision(3) << f << endl;
You may unset fixed using cout.unsetf(ios::fixed)

Problem with square root of (2147483647) in c++

I am calculating square root of 2147483647 by sqrt function.and the result must be a float value 46340.95 but my code returns the value 46341.
Can anyone tell me where is the problem?
i am using code :
double x=2147483647.0;
double y=sqrt(x);
cout<< y;
I get that same result. But, if I inject a setprecision, I get the right value:
#include <iostream>
#include <iomanip>
#include <cmath>
int main (void) {
double x=2147483647.0;
double y=sqrt(x);
std::cout << std::setprecision(10) << y << std::endl;
return 0;
}
gives me:
46340.95
In fact, if you use the folowing code:
#include <iostream>
#include <iomanip>
#include <cmath>
int main (void) {
double x=2147483647.0;
double y=sqrt(x);
std::cout << y << std::endl;
std::cout << std::setprecision(0) << std::fixed << y << std::endl;
std::cout << std::setprecision(1) << std::fixed << y << std::endl;
std::cout << std::setprecision(2) << std::fixed << y << std::endl;
std::cout << std::setprecision(3) << std::fixed << y << std::endl;
return 0;
}
you get:
46341
46341
46341.0
46340.95
46340.950
So it appears that the default setting (at least for my environment) is a precision of zero.
If you want a specific format, I suggest you explicitly request it.
The default precision for cout is not sufficient to show the fractional part of your result. Your result is 46340.95, which rounded to six digits of precision is 43641.0, and is displayed as 43641 by cout. To show more precision, set the precision of cout first:
double x=2147483647.0;
double y=sqrt(x);
cout.precision(9);
cout<< y;
On my system this shows a result of 46340.95.
This trivial code yields 46340.9:
#include <cmath>
#include <iostream>
int main()
{
float x = std::sqrt(2147483647);
std::cout << x << std::endl;
return 0;
}
What does your code look like?
(Just for the record: tested using GCC (g++) 4.5.2 on MacOS X 10.6.6.)