modf returns 1 as the fractional:

前端 未结 2 1780
别跟我提以往
别跟我提以往 2021-01-24 05:17

I have this static method, it receives a double and \"cuts\" its fractional tail leaving two digits after the dot. works almost all the time. I have noticed that when i

相关标签:
2条回答
  • 2021-01-24 05:39

    Here is a way without rounding:

    double double_cut(double d)
    {
        long long x = d * 100;
        return x/100.0;
    }
    

    Even if you want rounding according to 3rd digit after decimal point, here is a solution:

    double double_cut_round(double d)
    {
        long long x = d * 1000;
    
        if (x > 0)
            x += 5;
        else
            x -= 5;
    
        return x / 1000.0;
    }
    
    0 讨论(0)
  • 2021-01-24 05:56

    Remember floating point number cannot represent decimal numbers exactly. 2.3 * 100 actually gives 229.99999999999997. Thus modf returns 229 and 0.9999999999999716.

    However, cout's format will only display floating point numbers to 6 decimal places by default. So the 0.9999999999999716 is shown as 1.


    You could use (roughly) the upper error limit that a value represents in floating point to avoid the 2.3 error:

    #include <cmath>
    #include <limits>
    static double dRound(double d) {
       double inf = copysign(std::numeric_limits<double>::infinity(), d);
       double theNumberAfter = nextafter(d, inf);
       double epsilon = theNumberAfter - d;
    
       int factor = 100;
       d *= factor;
       epsilon *= factor/2;
       d += epsilon;
    
       double returnVal;
       modf(number, &returnVal);
       return returnVal / factor;
    }
    

    Result: http://www.ideone.com/ywmua

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