Is there a way to do this without using the stream? For example, something like this:
double a = 6.352356663353535;
double b = a.precision(5);
instead of:
double a = 6.352356663353535;
std::cout.precision(5);
std::cout << a << std::endl;
I am new to C++ and I am curious. Thanks, in advance.
By using the setprecision function, we can get the desired precise value of a floating-point or a double value by providing the exact number of decimal places. If an argument n is passed to the setprecision() function, then it will give n significant digits of the number without losing any information.
Precision: 15 to 17 significant digits, depending on usage. The number of significant digits does not depend on the position of the decimal point. Representation: The values are stored in 8 bytes, using IEEE 754 Double Precision Binary Floating Point format.
Double precision provides greater range (approximately 10**(-308) to 10**308) and precision (about 15 decimal digits) than single precision (approximate range 10**(-38) to 10**38, with about 7 decimal digits of precision).
Long double has a minimum precision of 15, 18, or 33 significant digits depending on how many bytes it occupies. We can override the default precision that std::cout shows by using an output manipulator function named std::setprecision() .
I've revised the code taking into account @john, @Konrad and @KennyTM's suggestions. I've check that it works with negative numbers.
#include <cmath>
#include <cstdio>
using namespace std;
int main()
{
double a = 6.352356663353535;
double intpart;
double fractpart = modf (a, &intpart);
fractpart = roundf(fractpart * 100000.0)/100000.0; // Round to 5 decimal places
double b = intpart + fractpart;
printf("%.5lf", b);
}
Outputs
6.35236
double
s are almost universally implemented as IEEE floating point numbers. Their precision depends on the number size only (in the case of double
, which is short for “double-precision floating point number”, it’s 53 bits). There is no way of manually setting the precision of a floating point number.
The display precision is always a property of the output formatting, never of the number. Don’t try to change the number via rounding, the operation makes no sense. You don’t need to reduce a number’s precision, except for display purposes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With