Is there a function to round a float in C or do I need to write my own?

后端 未结 7 1306
旧时难觅i
旧时难觅i 2020-11-27 07:02

Is there a function to round a float in C or do I need to write my own?

float conver = 45.592346543;

I would

相关标签:
7条回答
  • 2020-11-27 07:36

    There is a round() function, also fround(), which will round to the nearest integer expressed as a double. But that is not what you want.

    I had the same problem and wrote this:

    #include <math.h>
    
       double db_round(double value, int nsig)
    /* ===============
    **
    ** Rounds double <value> to <nsig> significant figures.  Always rounds
    ** away from zero, so -2.6 to 1 sig fig will become -3.0.
    **
    ** <nsig> should be in the range 1 - 15
    */
    
    {
        double     a, b;
        long long  i;
        int        neg = 0;
    
    
        if(!value) return value;
    
        if(value < 0.0)
        {
            value = -value;
            neg = 1;
        }
    
        i = nsig - log10(value);
    
        if(i) a = pow(10.0, (double)i);
        else  a = 1.0;
    
        b = value * a;
        i = b + 0.5;
        value = i / a;
    
        return neg ? -value : value;
    } 
    
    0 讨论(0)
提交回复
热议问题