有没有一种不太递归的方式来格式化数字?

发布于 2024-10-04 07:30:47 字数 371 浏览 0 评论 0原文

C# 中是否有与 C++ 的流操纵器等效的东西? 例如,

int decimalPlaces = 2;
double pi = 3.14159;
cout.precision(decimalPlaces);
cout << pi;

为了将数字格式化为字符串,必须将数字格式化为字符串,这感觉很奇怪。 例如

int decimalPlaces = 2;
double pi = 3.14159;
string format = "N" + decimalPlaces.ToString();
pi.ToString(format);

,这就是 C# 中的完成方式,还是我错过了什么?

Is there a C# equivalent of C++'s stream manipulators?
Eg

int decimalPlaces = 2;
double pi = 3.14159;
cout.precision(decimalPlaces);
cout << pi;

It feels weird having to format a number to a string in order to format a number to a string.
Eg

int decimalPlaces = 2;
double pi = 3.14159;
string format = "N" + decimalPlaces.ToString();
pi.ToString(format);

It that just how it's done in C#, or did I miss something?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

对岸观火 2024-10-11 07:30:48

我会稍微缩小它:

int decimalPlaces = 2;
double pi = 3.14159;
pi.ToString("N" + decimalPlaces);

此外,在打印之前您不必格式化数字。打印设备也将接受格式化结构。

I would shrink it slightly:

int decimalPlaces = 2;
double pi = 3.14159;
pi.ToString("N" + decimalPlaces);

Also, you don't have to format the number before printing it. The printing facilities will accept formatting constructs too.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文