The following is my console input/output.
Please enter a real number: -23486.33
Characters checked: 9
Thank you.
The real number you entered is -23486.3
The value I entered is -23486.33, but yet cout prints it as -23486.3.
The relevant code is below:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
// Function prototype (declaration)
string readDouble();
bool isValidDouble(string);
int main()
{
string value;
double number;
value = readDouble();
while (!isValidDouble(value)) {
cout << "The number you entered is not a valid integer." << endl;
value = readDouble();
}
number = atof(value.c_str());
cout << "Thank you." << endl
<< "The real number you entered is " << number << endl;
}
When debugging, I check the value of number right after the method call atof(value.c_str())l;. Number is shown to have a value of -23486.33. So what happens between that and the print out by cout? In no part of my code do I set the precision of cout or make it fixed.
If you have any questions, please let me know.
Have you tried
std::cout << std::setprecision(2) << number;
look at:
http://www.cplusplus.com/reference/iomanip/setprecision/
-23486.3 is displayed because std::cout prints only 6 digits by default.
To print back a number entered from standard input (convertion text → floating number → text), you can use set_precision with digits10 as precision:
double d = -23486.33;
int precision = std::numeric_limits<double>::digits10;
std::cout << std::setprecision(precision) << d << std::endl;
This displays:
-23486.33
To print a number with full precision (usually for convertion floating number → text → floating number), you can use set_precision with max_digits10 as precision:
double d = -23486.33;
int precision = std::numeric_limits<double>::max_digits10;
std::cout << std::setprecision(precision) << d << std::endl;
This displays:
-23486.330000000002
Here the printed number is not the same because -23486.33 doesn't have an exact representation in IEEE encoding (expressed in base 2 instead of base 10).
For more details with digits10 and max_digits10, you can read:
difference explained by stackoverflow
digits10
max_digits10
Set a precision when you output a double and keep precision explicitly when you compare them.
When you convert a string presentation of a DEC number to a double(float point number presentation), the data in the memory might not be mathematically equal to the string presentation. It's the best approximation by a float point number presentation, and vise versa.
You can set the precision to the maximum limit for double.
The code snippet is here:
#include <iostream>
#include <limits>
#include <iomanip>
using namespace std;
double number = ... // your double value.
cout << setprecision(numeric_limits<double>::digits10) << number << endl;
Related
I hope this is not a naive question. Is type conversion performed implicitly in c++? Because I have asked user to input a number in hexadecimal format, and then when i output that number to the screen without mentioning its format, it is displayed as a decimal format. Am I missing something here?
#include <iostream>
#include <iomanip> using namespace std;
int main() { int number = 0;
cout << "\nEnter a hexadecimal number: " << endl;
cin >> hex >> number;
cout << "Your decimal input: " << number << endl; number;
}
There's no type conversion between hexadecimal and decimal here. Internally your number will be stored in two's complimentary (a binary representation) no matter whether it has been read in as a hex or decimal number. Converting from a string of dec/hex to an integer and the other way around happens when the number is inputted/outputted.
With std::hex you tell the stream you tell the stream to change its default numeric base for integer I/O. Without it, the default is decimal. So if you only do it for std::cin, then it is reading in numbers as hex, but std::cout is still outputting decimal numbers. If you want it to also change its base to hexadecimal, you have to do the same with std::cout:
std::cout << std::hex << "Your hexadecimal input: " << number << std::endl;
how to print specific number of digits in c++?For example ,printing 8 digits totally(before and after decimal point combined)
Edit: For further clarification, setprecision sets the digits when i have decimal digits to display.I want to display integer 30 also as 30.000000 ,in 8 digits.
The setprecision command puts fixed no. of digits after decimal and i don't want that.
In short , I want an alternative of c command printf("%8d",N) in C++.
You can do it using setprecision() function from include iomanip and fixed like:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double d = 1000;
double t = d;
int dc=0;
while(t>0.9)
{
dc++;
t= t/10;
}
cout<<"dc:"<<dc<<endl;
cout << fixed;
std::cout << std::setprecision(dc);
std::cout << d;
return 0;
}
The setprecision() will not work fine every time So you have to use fixed as well.
You should use the c++ header iomanip what you want is the setprecision() function:
std::cout << std::setprecision(5) << 12.3456789 << std::endl;
outputs 12.346. It also has other modifiers you can find here
EDIT
If you want to print trailing 0s, you need to also use std::fixed. This says to use that number of digits, regardless of whether or not they are significant. If you want that to be the total number, you could figure out the size of the number, then change the precision you set it to based on that, so something like:
#include <iostream>
#include <iomanip>
#include <cmath>
int main()
{
double input = 30;
int magnitude = 0;
while(input / pow(10, magnitude))
{
++magnitude;
}
std::cout << std::fixed << std::setprecision(8 - magnitude) << input << std::endl;
return 0;
}
This returns 30.000000. You can also do something similar by outputting to a string, then displaying that string.
#include <iostream> using namespace std;
int main()
{
double x=5.0,y=4.0,z;
z=x+y;
cout<<x<<endl<<y<<endl<<z;
return 0;
}
The above program gives me the following output:
5
4
9
When I have declared the variables to be double and even z as double why do I get the output as integer value(9)??
cout is being helpful here: if the double value is a whole number, then it, by default, does not display a decimal separator followed by an arbitrary number of zeros.
If you want to display as many numbers as the precision that your particular double on your platform has, then use something on the lines of
cout.precision(std::numeric_limits<double>::max_digits10);
cout << fixed << x << endl;
Floating point numbers with no digits after the floating point are printed as integers by default.
To always show the floating point, use setiosflags(ios::showpoint).
You can combine that with fixed and setprecision(n) I/O flags to limit how many digits to print after the floating point. For example:
double d = 5.0;
cout << setiosflags(ios::showpoint) << d << endl; // prints 5.00000
cout << setiosflags(ios::showpoint) << fixed << setprecision(1)
<< d << endl; // prints 5.0
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float a = 3.14159;
double b = 3.14159;
cout.precision(6);
cout << a << endl; //3.14159
cout << b << endl; //3.14159
cout.precision(10);
cout << a << endl; //3.141590118
cout << b << endl; //3.14159
cout.precision(20);
cout << a << endl; //3.141590118408203125
cout << b << endl; //3.1415899999999998826
return 0;
}
Can anyone explain the difference between float and double?
How do we print float/double with dynamic precision?
Assuming I have your definition of dynamic correct something like this should work:
void print(float toPrint, int precision)
{
cout.precision(precision);
cout << toPrint <<endl;
}
cout.precision only changes the precision of the printing, it doesn't actually affect how precise the numbers are. If you print with more digits than your numbers have precision, you will get inaccurate digits.
Of course, cout.precision also only changes the maximum precision of the printing. To force it to print trailing zeros, do something like this:
void print(float toPrint, int precision)
{
cout.precision(precision);
cout << fixed;
cout << toPrint <<endl;
}
The difference between a float and a double is that a double is approximately twice as precise as a float. In general, a float has something like 7 or 8 digits of precision, and a double has 15 or 16 digits of precision.
If I'm reading your question correctly you are wondering why both floats and doubles lose precision after you adjust cout.precision.
This occurs because floating point numbers are stored in binary differently than normal whole numbers. A common example of why this matters is that the number 0.6 is stored in binary as 0011111100101.... This, like 0.6666666... in decimal, is an infinitely long number. Thus, your computer needs to decide at what point it should round/approximate the value. When you declare and initialize your floating point numbers a and b, the computer knows that it does not need to cram any value other than 3.14159 into the variable. However, when you then change cout.precision, the computer thinks it needs to round the floating point at a later location. Furthermore, floats are only 16 bits so it will almost always be less precise than the double, which is 32 bits. See here for their ranges.
Obviously to get the correct precision you shouldn't adjust cout.precision to be greater than the number of digits of your variable. However if you want to adjust the precision and just print out a bunch of zeroes after the end of your initial variable value, just use cout << fixed << setprecision(number). See below:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float a = 3.14159;
double b = 3.14159;
cout.precision(6);
cout << a << endl; //3.14159
cout << b << endl; //3.14159
cout << fixed << setprecision(10);
cout << a << endl; //3.141590118
cout << b << endl; //3.141590000
return 0;
}
Edit: Another option is to use limits.
It doesn't make sense to have a "dynamic precision" where all digits different from 0 are displayed. That mode would have issues with fractional numbers that have infinite decimal digits, like the result of 1.0 / 3.
The best you can do is to set the maximum precision you are willing to see with precision, just like in your example.
When I try and round digits using setprecision(2) in C++, numbers like "0.093" re returned- THREE, not two digits after the decimal! I cannot figure out why this is. I've included my very rudimentary code below, in case I am severely missing some point. Thanks!
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double tax = 0.06 ; //Tax Rate
float cost ; //Cost of item
float computed ; //Non-rounded tax
cout << "Enter the cost of the item: " ;
cin >> cost ;
computed = tax*cost;
cout << "Computed: $" << computed << endl;
cout << "Charged: $" << setprecision(2) << computed << endl; //Computed tax rounded to 2 decimal places
return 0;
}
This is because std::setprecision doesn't set the digits after the decimal point but the significant (aka "meaningful") digits if you don't change the floating point format to use a fixed number of digits after the decimal point. To change the format, you have to put std::fixed (documentaion) into your output stream:
cout << "Charged: $" << fixed << setprecision(2) << computed << endl;
From: http://www.cplusplus.com/reference/iomanip/setprecision/
The decimal precision determines the maximum number of digits to be written on insertion operations to express floating-point values. How this is interpreted depends on whether the floatfield format flag is set to a specific notation.
...
On the default floating-point notation, the precision field specifies the maximum number of meaningful digits to display in total counting both those before and those after the decimal point.
In your case: 0.093, 93 - two meaningful digits.
cout << fixed <<setprecision(6)<< a<<endl; // add whatever you want to round in the place of a