Long integer literals

I had to deal with code that computes with a large number, for example.

long foo = 6235449243234; 

It is hard to say what the order of magnitude is. I would like to write it

 long foo = 6_235_449_243_234; 

or

 long foo = @6 235 449 243 234; 

But C # does not have these features. How to make numeric literals more readable?

To comment

 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?

+6
source share
5 answers

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

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

Comments every time IMO. Otherwise, you just make the code bloated and less optimal:

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

You can write

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

But it is also impossible to read.

For numbers in variables when debugging, you can write a debugger visualizer .

+3
source

Comments - and if possible - use const or static readonly values ​​so that you only post / comment on the number in one place.

+1
source

Another (unjustified) way to do this:

 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); 
+1
source

Source: https://habr.com/ru/post/907659/


All Articles