You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C语言中为输出数字添加千位点分隔符

你需要自己实现千分位圆点格式化逻辑,C标准库没有原生支持自定义分隔符的数字格式化语法,以下是兼容性最优的实现方案:

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

int ticketVipCounter(int ticketVip){
    return ticketVip * 250000;
}

// 输入整数,输出带.千分分隔的字符串
void formatPrice(int num, char *output) {
    char rawNum[20];
    sprintf(rawNum, "%d", num);
    int len = strlen(rawNum);
    int outputIdx = 0;

    for (int i = 0; i < len; i++) {
        output[outputIdx++] = rawNum[i];
        // 剩余未遍历位数为3的倍数且不是最后一位时插入分隔符
        if (i != len - 1 && (len - i - 1) % 3 == 0) {
            output[outputIdx++] = '.';
        }
    }
    output[outputIdx] = '\0';
}

int main() {
    char priceStr[20];
    formatPrice(ticketVipCounter(4), priceStr);
    printf("Prices Is: %s", priceStr);
    return 0;
}

运行后输出结果为Prices Is: 1.000.000,完全符合需求。

如果你是在POSIX兼容环境(Linux/macOS等)下运行,也可以用locale修改千分分隔符的方案,代码更简洁:

#include <stdio.h>
#include <locale.h>
#include <langinfo.h>

int ticketVipCounter(int ticketVip){
    return ticketVip * 250000;
}

int main() {
    setlocale(LC_ALL, "");
    struct lconv *localeConfig = localeconv();
    localeConfig->thousands_sep = ".";
    localeConfig->grouping = "\x03";
    printf("Prices Is: %'d", ticketVipCounter(4));
    return 0;
}

注意该方案依赖运行环境的locale支持,部分Windows编译环境下可能不生效,优先选择第一种全平台兼容方案。

内容的提问来源于stack exchange,提问作者Nico A.L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 20:36:02