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

前端 未结 17 3054
孤城傲影
孤城傲影 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:25

    double f_round(double dval, int n)
    {
        char l_fmtp[32], l_buf[64];
        char *p_str;
        sprintf (l_fmtp, "%%.%df", n);
        if (dval>=0)
                sprintf (l_buf, l_fmtp, dval);
        else
                sprintf (l_buf, l_fmtp, dval);
        return ((double)strtod(l_buf, &p_str));
    
    }
    

    Here n is the number of decimals

    example:

    double d = 100.23456;
    
    printf("%f", f_round(d, 4));// result: 100.2346
    
    printf("%f", f_round(d, 2));// result: 100.23
    

提交回复
热议问题