Converting from Combobox double digit to int double digit - c#

Min = Convert.ToInt32(cbMin.SelectedItem);
Here's my issue, using that line to convert from the combobox to the integer variable. Right now, if i select "00" or "05" from my drop down the value only comes out as "0" or "5" It only seems to happen when a number STARTS with a "0"
Am i missing something?
PS: By the way, when I setup the combobox i just used the properties section on the side and filled out the collection. Just wanted to be sure that i threw that out there.

dont convert value to integer if you want leading zero make use of string
i.ToString("00")
try this out soltuon will work for you
final code is
string s = (Convert.ToInt32(cbMin.SelectedItem)).ToString("00")
EDIT
if you alredy assinged valeu with 0 than you just need to write
string Min = cbMin.SelectedItem.ToString();

Integers don't have leading zeros. They are numeric data types. The leading zero is only possible in a string data type.
int 0 is not the same as string "0"
int 1 is not the same as string "1"
If you need to output the value with the leading 0, and never use it in mathematical claculations, you should keep it as a string. Don't convert it to an int in the first place.
If you need it as an integer to do calculations, then you need to convert it to an int, but in places where you need the leading zero, format it. Convert it back to a string and use data formatting to get the leading zero.
"1".ToString("00") will result in "01".
"15".ToString("00") will result in "15".
For more information on formatting numeric data types, see the documentation here and the Custom Numeric Format Strings (as shown in my examples above) documentation here.

There is no sense make an integer 5 as 05 in C#. But if want a string has this format, you can do:
string Min = Convert.ToInt32(cbMin.SelectedItem).ToString("00");
Or
string Min = String.Format("{0:0#}", Convert.ToInt32(cbMin.SelectedItem));

Related

C# converting string to int goes wrong

I have a string that contains numbers, like so:
string keyCode = "1200009990000000000990";
Now I want to get the number on position 2 as integer, which I did like so:
int number = Convert.ToInt32(keyCode[1]);
But instead of getting 2, I get 50.
What am I doing wrong?
50 is the ascii code for char '2'. 0->48, 1->49 etc....
You can do
int number = keyCode[1]-'0';
You observed that when you do int n = Convert.ToInt32( '2' ); you get 50. That's correct.
Apparently, you did not expect to get 50, you expected to get 2. That's what's not correct to expect.
It is not correct to expect that Convert.ToInt32( '2' ) will give you 2, because then what would you expect if you did Convert.ToInt32( 'A' ) ?
A character is not a number. But of course, inside the computer, everything is represented as a number. So, there is a mapping that tells us what number to use to represent each character. Unicode is such a mapping, ASCII is another mapping that you may have heard of. These mappings stipulate that the character '2' corresponds to the number 50, just as they stipulate that the character 'A' corresponds to the number 65.
Convert.ToInt32( char c ) performs a very rudimentary conversion, it essentially reinterprets the character as a number, so it allows you to see what number the character corresponds to. But if from '2' you want to get 2, that's not the conversion you want.
Instead, you want a more complex conversion, which is the following: int n = Int32.Parse( keyCode.SubString( 1, 1 ) );
Well, You got 50 because it is the ascii code of 2.
You are getting it because you are pointing to a char and when c# converts a char to an int it gives back its ascii code. You should use instead int.Parse which takes a string.
int.Parse(keyCode[1].ToString());
or
int.Parse(keyCode.Substring(1,1));
You need
int number = (int)Char.GetNumericValue(keyCode[1]);
The cast is needed because Char.GetNumericValue returns a double.
As Ofir said, another method is int number = int.Parse(keyCode[1].ToString()).
This command can be explained like this: int is shorthand for Int32, which contains a Parse(string) method. Parse only works if the input is a string that contains only numbers, so it's not always the best to use unless TryParse (the method that checks whether you can parse a string or not) has been invoked and returns true, but in this case, since your input string is always a number, you can use Parse without using TryParse first. keyCode[1] actually implicitly converts keyCode to a char[] first so that it can retrieve a specific index, which is why you need to invoke ToString() on it before you can parse it.
This is my personal favorite way to convert a string or char to an int, since it's pretty easy to make sense of once you understand the conversions that are performed both explicitly and implicitly. If the string to convert isn't static, it may be better to use a different method, since an if statement checking whether it can be parsed or a try makes it take longer to code and execute than one of the other solutions.

how to add zeros for integer variable

I'm very new to c# programming. I want to know how to add leading zeros for a integer type in c#.
ex:
int value = 23;
I want to use it like this ;
0023
Thanks in advance
You can't. There's no such contextual information in an int. An integer is just an integer.
If you're talking about formatting, you could use something like:
string formatted = value.ToString("0000");
... that will ensure there are at least 4 digits. (A format string of "D4" will have the same effect.) But you need to be very clear in your mind that this is only relevant in the string representation... it's not part of the integer value represented by value. Similarly, value has no notion of whether it's in decimal or hex - again, that's a property of how you format it.
(It's really important to understand this in reasonably simple cases like this, as it tends to make a lot more difference for things like date/time values, which again don't store any formatting information, and people often get confused.)
Note that there's one type which may surprise you: decimal. While it doesn't consider leading zeroes, it does have a notion of trailing zeroes (implicitly in the way it's stored), so 1.0m and 1.00m are distinguishable values.
Basically you want to add padding zeros.
string format specifier has a very simple method to this.
string valueAfterpadding;
int value = 23;
valueAfterpadding = value.ToString("D4");
Console.WriteLine(valueAfterpadding );
this solve your problem. just google it.
Integer wont accept leading zeros, it will only hold the real value of the integer.
The best we to have leading zeros is to convert it to string.
If you need a 4 digit value always, use the .ToString formatting to add leading 0's.
int value = 23;
var result = value.ToString("0000");
or if you want to have a leading 00 to any number, better append 00 to the string equivalent of the integer.
int value = 23;
var result = "00" + value.ToString();
This is not a programming issue. Numbers have no leading zeroes.
There are two things here that you can do:
If it is a number, then format it on the way out.
If it is something like a code (article number etc.) - those are NOT NUMBERS.
The second point is important. Things like social security numbers, part numbers etc. are strings - with only numeric characters allowed. You never add or subtract them and you must be prepared for format changes. They are not integers or any other number form to start with.

Convert long Double to Int?

Trying to convert the following value:
9.40551020088303E+21
to
9405510200883031584406
I am a but lost on how to do this? Math.Round, (int)Value.
Edit: Ok i may be wrong here, but i am trying to convert this to 9405510200883031584406 in anyway possible, it can be a string, or different type.
The final result is a tracking number and what i am starting with is what the shipping company provides me with.
the closest thing I can think of is using BigInteger
double d = 9.40551020088303E+21;
BigInteger bi = new BigInteger(d);
Console.WriteLine(bi.ToString());
Output would be:
9405510200883030261760
What you're describing isn't possible. An int (Int32) data type has a maximum value of 2147483647.
the long (Int64) data type, can only go up to 9,223,372,036,854,775,807
an unsigned long (UInt64) can go to 18,446,744,073,709,551,615
The number is simply too large for any of those data types.
9,405,510,200,883,031,584,406 (Your value)
9,223,372,036,854,775,807 (Int64.MaxValue)
18,446,744,073,709,551,615 (UInt64.MaxValue)
If you just want to convert this to a string as in your question it can be a string, or different type. Than this should suffice.
decimal value = 9405510200883031584406m;
string str = value.ToString("F0");
However, this assumes you know the actual full number. You can't convert 9.40551020088303E+21 to a more precise value, if you don't know the trailing digits.
You can see how to format in Standard Numeric Format Strings
The fixed-point ("F) format specifier converts a number to a string of
the form "-ddd.ddd…" where each "d" indicates a digit (0-9). The
string starts with a minus sign if the number is negative. The
precision specifier indicates the desired number of decimal places. If
the precision specifier is omitted, the current
NumberFormatInfo.NumberDecimalDigits property supplies the numeric
precision.

Double to String Format text format

i have the follwing lines of code
double formId=2013519115027601;
txtEditFormID.Text = formid.ToString();
it gives me output
2.0135191150276E+15
if i write
txtEditFormID.Text = formId.ToString("0.0", CultureInfo.InvariantCulture);
it gives me
2013519115027600.0
but i want the label text
2013519115027601
how to do it?
I don't have enough information about the usage of your formId variable.
As it is shown above it seems an error to use a double datatype when there is no decimals to work on. So redefining your variable as a long datatype will be easy and the conversion will be the same.
long formId=2013519115027601;
txtEditFormID.Text = formid.ToString();
Not to mention the added benefit to your code to work with whole numbers instead of floating point numbers.
However, if you want to maintain the current datatype then
txtEditFormID.Text = formId.ToString("R");
The Round Trip Format Specifier
When a Single or Double value is formatted using this specifier, it is
first tested using the general format, with 15 digits of precision for
a Double and 7 digits of precision for a Single. If the value is
successfully parsed back to the same numeric value, it is formatted
using the general format specifier. If the value is not successfully
parsed back to the same numeric value, it is formatted using 17 digits
of precision for a Double and 9 digits of precision for a Single.
Your first option is to use data type as long or decimal . Something else you can do if you want to keep using double is this :
double formId = 2013519115027601;
string text = formId.ToString();
txtEditFormID.Text = text.Replace(".",string.Empty);
this will remove all the '.' chars
There are times where I want calculations handled in double but I want the result displayed as as an int or even rounded amount, so the question isn't so strange (assuming that the given sample is simplified in order to ask the question).
I was going to post sample code for rounding, but it makes more sense to just use the built-in method Math.Round(). You can cast to a long, as mentioned above, but you won't have rounding, if desired (which it usually is, IMHO).
txtEditFormId.Text = ((long)formId).ToString();

How to convert a string "001" to int 001

how do i convert a string of "001" to an int 001? using Convert.ToInt32() method or Int32.Parse() method gives the result as only 1
How could you have an int as 001? You could format it as a string with leading zeros, but the int itself is just a numeric representation. Keep in mind that the language needs a way to represent the int to you as a series of characters, and that it needs to be deterministic (because otherwise it would have no way to choose). So the standard is to not show any leading zeros.
You can't have an int with zeros in front like that - doesn't quite make sense. If the formatting is important you'll just have to leave it as a string.
1 is an integer, 001 is a string. If you are trying to display a 3-digit series as an id or similar and are incrementing you will need to convert your string "001" to an integer, increment it, then convert it back to a "0" padded string for display.
public string NextId(string currentId)
{
int i = 0;
if (int.TryParse(currentId, out i))
{
i++;
return(i.ToString().PadLeft(3,'0'));
}
throw new System.ArgumentException("Non-numeric string passed as argument");
}
There is a fundamental misunderstanding in your question. An int is a number, and in our numerical system, leading zeros on the left of the decimal point do not change the number and are therefore irrelevant. In other words, 1 is equal to 01 is equal to 001 is equal to 0001 and so forth... this may seem obvious, but it makes the point that 1 is the integer value. 001 is a string.
An integer cannot store the value 001. The result 1 is correct.
You need to elaborate on why you need the other zeros.
Whilst in byte form it will have a representation along the lines of 001 (or 0000000000000001), the runtime doesn't know which base you want to represent the number in, so the 2nd and 3rd columns (the other two zeros) are ambiguous.
an int will never be preceded with '0', only string is possible.
You can use Int32.ToString("000") to format an integer in this manner.
string one = a.ToString("000"); // 001
string two = b.ToString("000"); // 010
but you cant use like a integer 001.

Categories

Resources