Truncate a decimal value in C++

后端 未结 10 1724
萌比男神i
萌比男神i 2020-12-10 05:38

What\'s the easiest way to truncate a C++ float variable that has a value of 0.6000002 to a value of 0.6000 and store it back in the variable?

10条回答
  •  悲&欢浪女
    2020-12-10 05:57

    First it is important to know that floating point numbers are approximated. See the link provided by @Greg Hewgill to understand why this problem is not fully solvable.

    But here are a couple of solutions to the problem that will probably meet your need:

    Probably the better method but less efficient:

    char sz[64];
    double lf = 0.600000002;
    sprintf(sz, "%.4lf\n", lf); //sz contains 0.6000
    
    double lf2 = atof(sz);
    
    //lf == 0.600000002;
    //lf2 == 0.6000
    
    printf("%.4lf", lf2); //print 0.6000
    

    The more efficient way, but probably less precise:

    double lf = 0.600000002;
    int iSigned = lf > 0? 1: -1;
    unsigned int uiTemp = (lf*pow(10, 4)) * iSigned; //Note I'm using unsigned int so that I can increase the precision of the truncate
    lf = (((double)uiTemp)/pow(10,4) * iSigned);
    

提交回复
热议问题