简体   繁体   English

在C#代码中分隔大数字的数字

[英]Separating digits for large numbers in C# code

In C++ you can separate the digits for readability in your code with apostrophes: 在C ++中,您可以使用撇号将数字中的数字与可读性分开:

int num = 1'000'000;

In Ruby, you can use underscores: 在Ruby中,您可以使用下划线:

num = 1_000_000

Is there a similar syntax for C#? C#有类似的语法吗? I tried a few different searches but only came up with results for outputting or reading numbers in a particular format. 我尝试了一些不同的搜索,但只提出了以特定格式输出或读取数字的结果。

As of the time this answer is written, that feature does not exist in C#. 截至撰写本答案时,C#中不存在该功能。 However, there is a feature request for it, and it looks like it will be part of C# 7, which is the upcoming version. 但是,它有一个功能请求 ,看起来它将是C#7的一部分,这是即将推出的版本。

The feature request is listed on their C# 7 list of features , but you probably shouldn't assume 100% it will make it in. Things are subject to change. 功能请求列在他们的C#7功能列表中 ,但您可能不应该假设100%它将进入。事情可能会发生变化。

This won't help with int, but with decimal you can use: 这对int没有帮助,但是使用decimal可以使用:

decimal num1 = 1E06M; // 1000000
decimal num2 = 1.23e06m; // 1230000

Small but handy little feature introduced in C# 7.0 is the digit separator character, which takes the form of a single underscore (_). C#7.0中引入的小巧但便捷的小功能是数字分隔符,它采用单个下划线(_)的形式。 This separator can be used within any numeric literal that means of improving legibility. 此分隔符可用于任何数字文字,以提高易读性。 Digit separator in a numeric literal does not change the value in anyway. 数字文字中的数字分隔符无论如何都不会更改值。 Any given number is always the same to the common language run time, regardless of whether it uses separators or not. 无论是否使用分隔符,任何给定的数字始终与公共语言运行时相同。

// These two are equivalent.
var bigNumber      = 123456789012345678;
var bigNumberWithSplit = 123_456_789_012_345_678;

在此期间,您仍然可以这样做:

int num = Int32.Parse("1,000,000", NumberStyles.AllowThousands);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM