C語言將double/float 轉爲字符串(帶自定義精度)

char *double_to_string(double d, int decimal)
{

        decimal = decimal < 0 ? 0 : decimal;
        char *p;
        char dd[20];
        switch (decimal) {
        case 0:
                sprintf(dd, "%.0lf", d);
                break;
        case 1:
                sprintf(dd, "%.1lf", d);
                break;
        case 2:
                sprintf(dd, "%.2lf", d);
                break;
        case 3:
                sprintf(dd, "%.3lf", d);
                break;
        case 4:
                sprintf(dd, "%.4lf", d);
                break;
        case 5:
                sprintf(dd, "%.5lf", d);
                break;
        default:
                sprintf(dd, "%.6lf", d);
                break;

        }
        p = malloc(strlen(dd));
        strcpy(p,dd);
        return p;
}

需用到頭文件有:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

簡單用法:

double d = 3.1415926;
char dstr[20];
sprintf(dstr,"%.2lf",d);//將d 保留2位小數賦值給dstr

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章