定点数的动态格式化
Dynamic Formatting of a fixed point number
我需要格式化一个浮点数(表示为std::string
),其中输出最多有14位数字,包括整数部分和小数部分。
虽然限制为14位数字,但整数部分最多可以有14位数字(然后没有小数部分),小数部分最多可以有7位数字(然后整数部分有7位数字)
**Examples**
123
123.456
12345678901234
1234567.89
1234.5678901
1234567890123.4
1234567890123.456 // Invalid; Should be transformed to 1234567890123.4
123456789012345.6 // Invalid; Should be transformed to 12345678901234
我们的想法是保留length =< 14
,其中十进制数的最大数量是7。最后,我还需要添加千个分隔符。
目前,我尝试使用小数点分割字符串并提取数字的两个部分。(如无"."
,另行办理)然后检查整数部分和小数部分的尺寸。
然而,由于这不是直接的,所以在某些情况下会失败。
但是我的问题是:
有没有简单的方法,让我不用这些乱七八糟的东西?
这非常简单,似乎可以根据您的规范工作。
std::string format(string str)
{
// Are there any decimals?
int dot = str.find(".");
if (dot < 0)
{
return str.substr(0, 14);
}
std::string integral = str.substr(0, dot);
size_t intlength = integral.length();
// Too long to care about decimals?
if (intlength >= 14)
{
return integral.substr(0, 14);
}
// Keep at most seven decimals
std::string decimals = str.substr(dot + 1, 7);
size_t declength = decimals.length();
// Is concatenation short enough?
if (intlength + declength <= 14)
{
return integral + "." + decimals;
}
return integral + "." + decimals.substr(0, 14 - integral.length());
}
您可以使用Boost.Format。下面是一个通过测试用例的示例:
#include <iostream>
#include <iomanip>
#include <boost/format.hpp>
int main()
{
std::vector<std::string> examples = {
"123",
"123.456",
"12345678901234",
"1234567.89",
"1234.5678901",
"1234567890123.4",
"1234567890123.456",
"123456789012345.6"
};
std::string format = "%1$.15s";
for (auto example : examples)
{
std::cout << boost::format(format) % example << "n";
}
}
相关文章:
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- C++中的动态铸造故障
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 内联映射初始化的动态atexit析构函数崩溃
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- C++格式化输出问题
- 控制允许动态运行c++的并发操作数
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 输出没有重复元素的动态数组(收缩数组)C++
- C++为线程工作动态地分割例程
- 正在插入动态数组
- 在c++中使用动态分配的问题
- C++中的动态对象与非动态对象
- 如何在动态数组上使用搜索函数
- 视觉studo 2019中的漫画和静态/动态绑定
- 从C++中的数字输入动态创建矩阵
- 如何从QToolBox中动态创建的QLineEdit中获取文本
- 定点数的动态格式化