gpt4 book ai didi

C# 相当于 imbue 和 numpunct

转载 作者:行者123 更新时间:2023-11-30 02:29:10 24 4
gpt4 key购买 nike

我正在尝试在 C++ 中找到与以下内容等效的 C#。这纯粹是为了好玩

#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

我可以为此编写大量代码,但我想知道是否有一种简单的方法可以做到这一点。

最佳答案

来自 the documentation ,在指定自定义格式时,逗号(强调我的):

Serves as both a group separator and a number scaling specifier. As a group separator, it inserts a localized group separator character between each group. As a number scaling specifier, it divides a number by 1000 for each comma specified.

所以它导致数字被分组为 3 位数字。如果您想制作自己的格式,则需要将逗号括在单引号中以将其呈现为文字字符串。例如:

Console.WriteLine(bignum.ToString("##','###','##','#0"));
Console.WriteLine(bignum.ToString("#','####','###0"));

将输出:

12,345,67,89
1,2345,6789

另一种选择是将 NumberFormatInfo 对象与 NumberGroupSizes 一起使用属性(property)。例如:

var nfi = new System.Globalization.NumberFormatInfo();
//First group is 2 digits, the rest are 3 digits
nfi.NumberGroupSizes = new int[] { 2, 3 };

Console.WriteLine(bignum.ToString("#,#0", nfi));

关于C# 相当于 imbue 和 numpunct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39863095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com