How do I restrict a float value to only two places after the decimal point in C?

前端 未结 17 3064
孤城傲影
孤城傲影 2020-11-22 03:22

How can I round a float value (such as 37.777779) to two decimal places (37.78) in C?

17条回答
  •  不要未来只要你来
    2020-11-22 03:45

    this function takes the number and precision and returns the rounded off number

    float roundoff(float num,int precision)
    {
          int temp=(int )(num*pow(10,precision));
          int num1=num*pow(10,precision+1);
          temp*=10;
          temp+=5;
          if(num1>=temp)
                  num1+=10;
          num1/=10;
          num1*=10;
          num=num1/pow(10,precision+1);
          return num;
    }
    

    it converts the floating point number into int by left shifting the point and checking for the greater than five condition.

提交回复
热议问题