如何在Windows上的C中为double添加千位分隔符?

前端之家收集整理的这篇文章主要介绍了如何在Windows上的C中为double添加千位分隔符?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用MPFR库对大数字进行计算,但也返回小数点后8位数的双精度数.

我mpfr_sprintf一个char数组的数字,所以精度或任何东西都不会丢失.
一切都很好,除了我没有在文档中找到任何千分隔符选项(或我错过了它).

鉴于像20043.95381376这样的数字,我想代表它像20,043.95381376以获得更好的可读性.

或者数字164992818.48075795为164,992,818.48075795

我读到了应该添加到printf / sprintf的撇号,但这似乎是一个UNIX / POSIX的东西,我是一个Windows用户.

因为在内部我将数字打印为字符串,我认为我能做的是编写一个自定义实现,根据数字(> 1000> 10000> 100000等)自动添加逗号,但后来我意识到这样的功能strncpy或strcpy将基本上替换,而不是将逗号添加到所需位置.以下是我如何回答如何做到这一点.

我该怎么做?

解决方法

您需要实现将double值转换为string并检查该字符串的每个字符,然后将其与分隔符一起复制到输出字符串.

像这样的东西:

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

int thousandsep(double in,char* out_str,size_t out_len,unsigned int precision) {
    char in_str[128],int_str[128],format[32];
    size_t dlen,mod,i,j;
    int c;

    snprintf(format,sizeof format,"%%.%df",precision);
    snprintf(in_str,sizeof in_str,format,in);
    snprintf(int_str,sizeof int_str,"%d",(int)in);

    dlen = strlen(in_str);
    mod = strlen(int_str) % 3;
    c = (mod == 0) ? 3 : mod;

    for (i=0,j=0; i<dlen; i++,j++,c--) {
        if (j >= out_len - 1) {
            /* out_str is too small */
            return -1;
        }

        if (in_str[i] == '.') {
            c = -1;
        } else if (c == 0) {
            out_str[j++] = ',';
            c = 3;
        }

        out_str[j] = in_str[i];
    }
    out_str[j] = '\0';

    return 0;
}

然后像这样使用它:

char out_str[64];

if (thousandsep(20043.95381376,out_str,sizeof out_str,8) == 0)
    printf("%s\n",out_str);       /* 20,043.95381376 */

if (thousandsep(164992818.48075795,out_str);       /* 164,818.48075795 */

if (thousandsep(1234567.0,0) == 0)
    printf("%s\n",out_str);       /* 1,234,567 */

注意:我假设如果你在Windows上,你可能正在使用MSVC,所以这个解决方案应该在C89编译器上工作.

猜你在找的Windows相关文章