C++数据格式化1 - uint转换成字符串 & double转换成字符串

1. 关键词

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

2. strfmt.h

#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

#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. 测试代码

#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. 运行结果

--------------------------------------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。

posted @ 2024-06-18 22:54  陌尘(MoChen)  阅读(44)  评论(0编辑  收藏  举报