c++ - 使用逗号打印数字C++
问题描述
我真的在发帖,因为我过去曾有过这个问题,发现很难找到答案。最终我确实偶然发现了一些东西,但这不是最干净的东西。我最终在我的编码知识方面取得了进步,我能够制作一个看起来很干净的函数。在这里发帖分享,希望对其他人有所帮助。
解决方案
编辑:由于处理负数的问题而进行了多次编辑,解决方案确实是一种解决方法,但按照我的标准看起来仍然很整洁。
我基本上依赖于 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);
推荐阅读
- javascript - 为什么我的过渡在引导导航上不起作用?
- excel - 如何根据单元格中的值将Excel行拆分为多个
- python - 安装包时出现 Conda 和 Anaconda 错误 (pythonOCC)
- javascript - 任何人都可以解释如何在这个功能组件中使用目标属性
- java - 在适配器的多个 TextView 中显示字符串
- python - 为特定国家生成随机坐标
- javascript - 如何使用自定义字母表生成 GUID,其行为类似于 MD5 哈希(在 JavaScript 中)?
- primefaces - primefaces 8升级后输入数字组件不起作用
- php - 选择输入 TYPO3 v9 Symfony 命令
- flask-migrate - 如何使用烧瓶迁移创建 mssql VIEW 模型?