c ++:用逗号格式化数字? [英] c++: Format number with commas?

查看:289
本文介绍了c ++:用逗号格式化数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个方法,它将获取一个整数,并返回一个以逗号格式化的整数的 std :: string

I want to write a method that will take an integer and return a std::string of that integer formatted with commas.

示例声明:

std::string FormatWithCommas(long value);

使用示例:

std::string result = FormatWithCommas(7800);
std::string result2 = FormatWithCommas(5100100);
std::string result3 = FormatWithCommas(201234567890);
// result = "7,800"
// result2 = "5,100,100"
// result3 = "201,234,567,890"

使用逗号将字符串格式化为数字的C ++方法是什么?

What is the C++ way of formatting a number as a string with commas?

(Bonus会处理 double s。)

(Bonus would be to handle doubles as well.)

推荐答案

#include <iomanip>
#include <locale>

template<class T>
std::string FormatWithCommas(T value)
{
    std::stringstream ss;
    ss.imbue(std::locale(""));
    ss << std::fixed << value;
    return ss.str();
}

免责声明:可移植性可能是一个问题,应该可以查看传递时使用的语言环境

Disclaimer: Portability might be an issue and you should probably look at which locale is used when "" is passed

这篇关于c ++:用逗号格式化数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆