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

后端 未结 3 1928
半阙折子戏
半阙折子戏 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 
    #include 
    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
    

提交回复
热议问题