首页 > 解决方案 > 使用逗号打印数字C++

问题描述

我真的在发帖,因为我过去曾有过这个问题,发现很难找到答案。最终我确实偶然发现了一些东西,但这不是最干净的东西。我最终在我的编码知识方面取得了进步,我能够制作一个看起来很干净的函数。在这里发帖分享,希望对其他人有所帮助。

标签: c++stringformatting

解决方案


编辑:由于处理负数的问题而进行了多次编辑,解决方案确实是一种解决方法,但按照我的标准看起来仍然很整洁。

我基本上依赖于 to_string 函数,然后在必要时添加逗号。

inline string printWithCommas(unsigned int number) {
    string temp = to_string(number);
    unsigned int numLength = temp.size();

    temp.reserve((numLength - 1) / 3 + numLength);
    for (unsigned int i = 1; i <= (numLength - 1) / 3; i++)
        temp.insert(numLength - i * 3, 1, ',');
    
    return temp;
}

对于可能为负数的整数。

inline string printWithCommas(int number) {
    if (number < 0)
        return string("-").append(printWithCommas((unsigned int)(number*-1));
    return printWithCommas((unsigned int)number);
}

对于浮点数和双精度数,它仅针对 numLength 的初始化而改变。

inline __device__ __host__ string printWithCommas(long double number) {
    if (number < 0)
        return string("-").append(printWithCommas(number * -1));

    string temp = to_string(number);
    unsigned int numLength = temp.find('.');

    temp.reserve((numLength - 1) / 3 + numLength);
    for (unsigned int i = 1; i <= (numLength - 1) / 3; i++)
        temp.insert(numLength - i * 3, 1, ',');

    return temp;
}

在我的方法文件中,我为每种数据类型都重载了函数,以避免与隐式转换混淆。就像:

inline std::string printWithCommas(int number);
inline std::string printWithCommas(long int number);
inline std::string printWithCommas(long long int number);

inline std::string printWithCommas(unsigned int number);
inline std::string printWithCommas(long unsigned int number);
inline std::string printWithCommas(long long unsigned int number);

inline std::string printWithCommas(float number);
inline std::string printWithCommas(double number);
inline std::string printWithCommas(long double number);

推荐阅读