简体   繁体   中英

long integer literals

I had to deal with the code that does calculation with big number eg

long foo = 6235449243234;

This is hard to tell what is the order of magnitude. I'd like to write it

long foo = 6_235_449_243_234;

Or

long foo = @6 235 449 243 234;

But C# doesn't have these features. How to make number literals more readable?

Comment it

long foo = 6235449243234; // 6 23...

Convert it from string

long foo = LiteralConverter.toLong(@"6_235_449_243_234");
int mask = LiteralConverter.toInt("b0111_0000_0100_0000");

Any other options?

Define named constants for these literals, and use comments to explain what the number represents.

class MyClass {
    ///
    /// This constant represents cost of a breakfast in Zimbabwe:
    /// 6,235,449,243,234
    ///
    const long AvgBreakfastPriceZimbabweanDollars = 6235449243234;
}

Comments every time IMO. Otherwise, you're just making the code bloated and less than optimal:

long foo = 6235449243234; // 6,235,449,243,234

You could write

long lNumber = (long)(6e12 + 235e9 + 449e6 + 243e3 + 234);

But that is not really readable either.

For numbers in variables when you are debugging you could write a debugger visualizer .

注释 - 如果可能 - 使用conststatic readonly值,以便您只在一个地方声明/注释该数字。

Another (unrecommended) way of doing it:

static long Parse(params int[] parts)
{
    long num = 0;
    foreach (int part in parts)
        num = num * 1000 + part;
    return num;
}

long foo = Parse(6,235,449,243,234);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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