1
我试图在C++中找到C#等价物。这纯粹是为了好玩C#等价于imbue和numpunct
#include <iomanip>
#include <iostream>
#include <tchar.h>
class CommaSep : public std::numpunct<TCHAR>
{
public:
CommaSep(TCHAR thousands_sep, const char* grouping)
:m_thousands_sep(thousands_sep),
m_grouping(grouping){}
protected:
TCHAR do_thousands_sep() const{return m_thousands_sep;}
std::string do_grouping() const {return m_grouping;}
private:
TCHAR m_thousands_sep;
std::string m_grouping;
};
int main()
{
double number = 1234567.1235;
std::locale comma_locale(std::locale(), new CommaSep(_T(','), "\03"));
std::locale indian_locale(std::locale(), new CommaSep(_T(','), "\02\02\03"));
std::locale weird_locale(std::locale(), new CommaSep(_T(','), "\02\01\03"));
std::wcout.imbue(comma_locale);
std::wcout << std::setprecision(2) << std::fixed << number << std::endl;
std::wcout.imbue(indian_locale);
std::wcout << std::setprecision(2) << std::fixed << number << std::endl;
std::wcout.imbue(weird_locale);
std::wcout << std::setprecision(2) << std::fixed << number << std::endl;
}
结果是
1,234,567.12
123,45,67.12
1,234,5,67.12
这不正是我告诉它。我在C#中尝试了以下内容。该代码是小了很多(万岁),但编译器会忽略格式和做自己的事(嘘嘶)
namespace imbuecs
{
class Imbue
{
static void Main(string[] args)
{
int bignum = 123456789;
System.Console.WriteLine(bignum.ToString("########0"));
// Indian
System.Console.WriteLine(bignum.ToString("##,###,##,#0"));
System.Console.WriteLine(bignum.ToString("###,###,##0"));
// Chinese
System.Console.WriteLine(bignum.ToString("#,####,###0"));
}
}
}
我有什么
123456789
123,456,789 expected 12,345,67,89
123,456,789
123,456,789 expected 1,2345,6789
我可以写的代码庞大的大片为此,但我想知道是否有一个简单的方法来做到这一点。
“是小了很多” - 你可以用C写有完全错误的代码++太,这将是更短的太:)。如果你真的关心你应该用适当的'CultureInfo'做特定于区域的格式,而不是某些手动解决方案。 –
CultureInfo不会执行奇怪的语言环境,这是我通常使用它的原因。有时我必须在非标准位置显示分隔符。 – cup