Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the precision of a double without using stream (ios_base::precision)

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.

like image 272
programmingNoob Avatar asked Sep 10 '12 09:09

programmingNoob


People also ask

How do you set double precision in C++?

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.

What is the precision of double data type?

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.

What is double precision value?

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).

What is the precision of long double in C++?

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() .


2 Answers

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
like image 142
Phillip Ngan Avatar answered Oct 19 '22 01:10

Phillip Ngan


doubles 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.

like image 21
Konrad Rudolph Avatar answered Oct 19 '22 02:10

Konrad Rudolph