Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

1. 关键词

C++ 数据格式化 字符串处理 std::string int double 跨平台

2. strfmt.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#pragma once

#include <string>
#include <cstdint>
#include <sstream>
#include <iomanip>

namespace cutl
{
/**
* @brief Format uint64 value to a string with a given width and fill character.
*
* @param val the value to be formatted.
* @param width the width of the formatted string.
* @param fill the fill character of the formatted string, default is '0'.
* @return std::string the formatted string.
*/
std::string fmt_uint(uint64_t val, uint8_t width = 0, char fill = '0');
/**
* @brief Format double value to a string with a given precision.
*
* @param val the value to be formatted.
* @param precision the precision of the formatted string, default is 2.
* @return std::string the formatted string.
*/
std::string fmt_double(double val, int precision = 2);
} // namespace cutl

3. strfmt.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <sstream>
#include <iomanip>
#include <bitset>
#include "strfmt.h"

namespace cutl
{
std::string fmt_uint(uint64_t val, uint8_t width, char fill)
{
std::stringstream ss;
ss << std::setfill(fill) << std::setw(width) << val;
return ss.str();
}

std::string fmt_double(double val, int precision)
{
std::stringstream ss;
ss << std::setiosflags(std::ios::fixed) << std::setprecision(precision) << val;
return ss.str();
}
} // namespace cutl

4. 测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
#include "common.hpp"
#include "strfmt.h"

void TestFormatUintAndDouble()
{
PrintSubTitle("TestFormatUintAndDouble");

std::cout << "fmt_uint 1: " << cutl::fmt_uint(12) << std::endl;
std::cout << "fmt_uint 2: " << cutl::fmt_uint(12, 4) << std::endl;
std::cout << "fmt_uint 3: " << cutl::fmt_uint(12, 4, 'x') << std::endl;
std::cout << "fmt_double 1: " << cutl::fmt_double(3.141592653) << std::endl;
std::cout << "fmt_double 2: " << cutl::fmt_double(3.141592653, 3) << std::endl;
}

5. 运行结果

1
2
3
4
5
6
--------------------------------------TestFormatUintAndDouble---------------------------------------
fmt_uint 1: 12
fmt_uint 2: 0012
fmt_uint 3: xx12
fmt_double 1: 3.14
fmt_double 2: 3.142

6. 源码地址

更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。

推荐阅读
C++数据格式化2 - 将文件大小转换为人类易读的格式 C++数据格式化2 - 将文件大小转换为人类易读的格式 C++数据格式化3 - 格式化时间区间(使用时长) C++数据格式化3 - 格式化时间区间(使用时长) C++数据格式化4 - 格式化时间戳 C++数据格式化4 - 格式化时间戳

评论