This is a little hard to read:
int x = 100000000;
Is there an easy way to write:
int x = 100,000,000;
So that the scale is obvious?
Please note this is NOT about formatting the output.
This is a little hard to read:
int x = 100000000;
Is there an easy way to write:
int x = 100,000,000;
So that the scale is obvious?
Please note this is NOT about formatting the output.
Starting with C#7 you will be able to use the underscore-char (_
) to seperate digit groups. The underscore can be placed anywhere in a number. A simple example:
const int MILLION = 1_000_000;
You can place the _
anywhere you want and can even combine it with integer literals:
const int USHORT_MAX = 0xFF_FF;
Or even with floats and decimals, even after the decimal sign:
const decimal SMALL_VALUE = 0.000_000_001;
Is there any easy way to write
100,000,000
No. It is not possible to put commas in numeric.
Comma and other similar things are for presentation purpose. If you are worried about code readability then either declare constants with name like MILLION
, TEN_MILLIONS
etc or simply name the variable to represent value.
If the purpose is to help the reader understand the code, then code comments may be appropriate, e.g.
int number = 1000000; //1,000,000
If you think scientific notation is easier to read, you could try
int number = 1 * 10^6;
or
int number = (int) 1E+6;
Constants like this are computed at compile time and do not affect performance.
Unfortunately you can't have commas in your int
declarations. Probably the best thing to add something like this at the beginning of your code:
const int oneMillion = 1000000;
Then just set int x = oneMillion;
If you'd like int y
to equal 2 million, then just set int y = 2 * oneMillion;
That's best practice (in my experience).
Does that help?
EDIT:
For more elaborate integers, you can try something like this:
const int thousand = 1000;
const int million = 1000000;
int x = 1 * million
+ 233 * thousand
+ 456;
It's not the prettiest, but perhaps it suits your readability needs. It also doesn't affect performance nearly as much as Int32.Parse("100,000,000");
int x = Int32.Parse("100,000,000", System.Globalization.NumberStyles.Number);
Whether or not that's more readable is a personal preference, I suppose.
You could create your own class for your number, something like this.
public class MyNumber
{
long? _myValue = null;
public MyNumber(string amount)
{
long result = 0;
if (long.TryParse(amount.Replace(",", ""), out result))
{
_myValue = result;
}
else
_myValue = 0;
}
public bool HasValue()
{
if (_myValue.HasValue) return true;
return false;
}
public long Value()
{
if (this.HasValue())
{
return _myValue.Value;
}
else
{
return 0;
}
}
}
Then you could call it like this.
MyNumber myValue = new MyNumber("9,999,100");
if (myValue.HasValue())
MessageBox.Show("Value Is " + myValue.Value().ToString());