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

后端 未结 3 1915
半阙折子戏
半阙折子戏 2020-12-19 09:40

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);
相关标签:
3条回答
  • 2020-12-19 10:18

    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
    
    0 讨论(0)
  • 2020-12-19 10:30

    A double always has the same internal precision (most probably 53 bits of binary precision), no matter what you do. It is only when writing out the double as text in decimal form where you can control the decimal precision of the output. So no, you cannot set the precision of a binary double precision number to anything else than it's native precision (let aside a decimal precision).

    If all you want is round a number to a given number of decimal digits, then consult Phillip's answer (but with the ammendments that john and Konrad made in their comments, of course). But note that this doesn't change the preicision of the underlying type and all computations with this number will be performed in binary double precision. Also such a rounded decimal number doesn't need to be represented exactly in the underlying binary floating point type.

    If you really want to perform exact decimal arithmetic, then you have to look for third-party libraries providing actual decimal floating point types.

    0 讨论(0)
  • 2020-12-19 10:39

    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.

    0 讨论(0)
提交回复
热议问题