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

后端 未结 7 1401
旧时难觅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:20

    As Rob mentioned, you probably just want to print the float to 1 decimal place. In this case, you can do something like the following:

    #include 
    #include 
    
    int main()
    {
      float conver = 45.592346543;
      printf("conver is %0.1f\n",conver);
      return 0;
    }
    

    If you want to actually round the stored value, that's a little more complicated. For one, your one-decimal-place representation will rarely have an exact analog in floating-point. If you just want to get as close as possible, something like this might do the trick:

    #include 
    #include 
    #include 
    
    int main()
    {
      float conver = 45.592346543;
      printf("conver is %0.1f\n",conver);
    
      conver = conver*10.0f;
      conver = (conver > (floor(conver)+0.5f)) ? ceil(conver) : floor(conver);
      conver = conver/10.0f;
    
      //If you're using C99 or better, rather than ANSI C/C89/C90, the following will also work.
      //conver = roundf(conver*10.0f)/10.0f;
    
      printf("conver is now %f\n",conver);
      return 0;
    }
    

    I doubt this second example is what you're looking for, but I included it for completeness. If you do require representing your numbers in this way internally, and not just on output, consider using a fixed-point representation instead.

提交回复
热议问题