Convert ComboBox to Decimal, C# - c#

I am trying to create a combobox that contains text and when each text is chosen the text will equal a decimal and later be used in a math code. I am using C# inside Visual Studio.
I am a beginner and any help will be greatly appreciated.
Thanks,
Royal

That should be reasonably simple. You can use Decimal.Parse() to convert the selected string value to a decimal:
decimal val = Decimal.Parse(someComboBox.SelectedItem.ToString());

If you know that the string is definately a Decimal you can use Justin's answer, if you are unsure if it is a Decimal you could also try:
decimal ParseDecimal(string str){
decimal number;
if(Decimal.TryParse(str, out number)
{
return number;
}
return decimal.MinValue (or any other value that you know to check against)
}
Where the string you pass into the method is the combo box string.

Are you looking to convert the input string to decimal? This may help. http://msdn.microsoft.com/en-us/library/59095yyw.aspx and also Decimal.TryParse http://msdn.microsoft.com/en-us/library/9zbda557.aspx

or if you are sure you can use Convert method:
decimal val =
Convert.ToDecimal(comboBox1.SelectedItem.ToString());
But becuase you said you are unsure about what string value is (or is a decimal, or a dobule, or a simple stirng, or ...) it would be better to use Darren`s version of checking, which will check if the string is a actual decimal value. If it is, it will go into the brackets (and you can do something then), if its not, then it will go over if statement (you can add an else statement to do something else.
Mitja

Related

C# Convert int to string and use in a Label

I have the following scenario.I am using App.config in Winforms and I have a value that is set to int (In settings). I want to use this value as a label text.
Am I correct that labels can only display string values?
This is what I have done here but not getting expected result (value to the label):
int ExclRate = Properties.Settings.Default.PriorExclTimer;
string ExclTime = ExclRate.ToString();
ExclTime = label60.Text;
PriorExclTimer is the type of the value in app.config.
I can make this work if I set the value in app.config to string, but that means I would have to convert from string to int in a much more sensitive part of the program, and I would rather not have to do that if possible. This is that line that works:
label60.Text = Properties.Settings.Default.PriorExclTimer;
I'm very new to C#, so I am really feeling my way around. Thanks...
In C# you cannot directly assign int to string. It has to always undergo conversion (either parse string to integer, or get a string out of integer).
As you say it's better to convert integer to a string for display purposes. Labels cannot directly show integer, so you will always need to convert it, or write some wrapper class if it's not enough.
Be aware that ToString() is culture specific, i.e. it will use the culture from the current thread. It might or might not be what you want. If you want InvariantCulture you can use ToString(CultureInfo.InvariantCulture).
P.S. As mentioned in the comments you can do various tricks like ExclRate + "", or in C#6 ${ExclRate}, but they are all basically converting an integer to string. I guess they all call ToString() inside.
int ExclRate = Properties.Settings.Default.PriorExclTimer;
label60.Text = ExclRate.ToString();
Code above will give you exception if PriorExclTimer is null or empty. So better you use int.TryParse to assign it to int. Not in this case, but ToString does not handle the null case, it gives exception. So you should try Convert.ToString instead.
While doing string manipulations you have to take care of culture and case (string case sensitive or insensitive)
This works for me:
int ExclRate = Properties.Settings.Default.PriorExclTimer;
label60.Text = ExclRate.ToString();
Many thanks for the insights on this topic. I will be manipulating data to and from a string a good bit for the project I am working on...

Convert.ToInt32(String) in C# not working?

I have a text box named textBox1, and In a certain case, I want to convert the string in the textbox to an integer for later use as an integer.
It's throwing an error that I can't even understand. Here is a screenshot:
(Per Request) The code is:
this.textBox1.Text = string.Concat(Int.Where(c => Char.IsNumber(c)));
this.textBox1.Text = Convert.ToInt32(this.textBox1.Text);
I would really appreciate it if you could give me an answer or fix to my code, and explain why it doesn't/does work.
Convert.ToInt32 will, by design, return an integer, not a string.
If you're just storing the result back into the text box, there's no reason at all to convert it to a number only to convert it back to a string.
This would really only be useful if you wanted to do:
int value = Convert.ToInt32(this.textBox1.Text);
That being said, you might want to use Int32.TryParse instead. This allows you to check for formatting errors instead of having exceptions raised if the user types inappropriate values.

Formatting textbox c# and using it unformatted value

I´m using some textboxes to show totals, subtotals and discounts. I´m converting decimals to string to represent them in the textbox. Also, I would like to have the "$" at the beginning.
I have achieved this by using this:
tbx_total.Text = total.ToString("$ ##0.##");
Graphically, this is working great, but my big problem is that I need that textbox value to calculate other ones. Basically, I get a formatting error during runtime when I try to convert that textbox text to decimal. Obviously, this is due to the ToString("$ ##0.##") format. Is there any way to get the value without the format?
One simple solution will be:
tbx_total.Text = total.ToString("$ ##0.##");
tbx_total.Tag = total;
Then use tbx_total.Tag property for further usage.
When reading it back in you can parse with NumberStyles to get your desired effect. There is a number of bit-wise operations on NumberStyles so I suggest researching how to use them for more flexibility:
double.Parse(total, NumberStyles.Currency);
Also I tend to like this for formatting currency a bit more but purely stylistic.
String.Format("{0:C}", total);
Note: Parsing back and forth does incur some overhead so depending on the amount of data it may be more wise to offload the value to an object and reference that when you need the decimal value again.
As an alternative, you can do this, whenever you read the value:
double value = 0;
if (!double.TryParse(tbx_total.Text.TrimStart(new char[] { '$', ' ' }), out value))
{
//Ooops... not a valid number
}
So here you basically remove the added '$' and space before the number enabling you to parse it as a double. This way you can check if the number has been entered correctly (provided that the user can edit the textbox.
I think you should store your original values (decimal) in a DataTable or some other collection and use these values to calculate what you need.
So you can format decimal values in any format you like without warry about how to convert back from strings.

Convert string value into decimal with proper decimal points

i have value stored in string format & i want to convert into decimal.
ex:
i have 11.10 stored in string format when i try to convert into decimal it give me 11.1 instead of 11.10 .
I tried it by following way
string getnumber="11.10";
decimal decinum=Convert.ToDecimal(getnumber);
i tried this also
decinum.ToString ("#.##");
but it returns string and i want this in decimal.
what could be the solution for this?
As already commented 11.1 is the same value as 11.10
decimal one=11.1;
decimal two=11.10;
Console.WriteLine(one == two);
Will output true
The # formatter in the to string method means an optional digit and will supress if it is zero (and it is valid to suppress - the 0 in 4.05 wouldn't be suppressed). Try
decinum.ToString("0.00");
And you will see the string value of 11.10
Ideally you actually want to use something like
string input="11.10";
decimal result;
if (decimal.TryParse(input,out result)) {
Console.WriteLine(result == 11.10);
} else {
// The string wasn't a decimal so do something like throw an error.
}
At the end of the above code, result will be the decimal you want and "true" will be output to the console.
this will work perfectly
string getnumber = "11.10";
decimal decinum = Math.Round(Convert.ToDecimal(getnumber), 2);
A decimal datatype stores a value. The value of 11.1 is identical to that of 11.10 - mathemtically, they're the exact same number, so it's behaving properly.
What you seem to want is to display the number as 11.10, but that's up to the code that displays it - I don't know if you're writing to log file, displaying on a web-page or any other format - but that is independent of the internal representation of the decimal datatype.
there is no solution, This is expected behaviour.
11.10 in string = 11.1 in number
you cant store zeros on the decimal part, otherwise 11.10 would be different than 11.100, which is true if you are talking about strings but not if you are talking about numbers.
I think your problem is on a presentation level only. Why dont you explain better what you want to do.
11.10 expressed as a decimal is 11.1, just like it is 11.100000000000000000000000000000000000.
For mathematical processes, don't worry about how it displays itself. If you are displaying the value then converting it into a string is no biggie either. Remember that
decinum.ToString ("#.##");
is returning a string (from the 'ToString' function) and not converting the 'decinum' to a string.
string getnumber = "11.10";
double decinum = double.Parse(getnumber);

C# Input Validation Check for positive numbers

I am learning C# and stuck on a problem where I have to check if the user input a VALID currency amount. i.e. no alphabetical character and no negative numbers.
So far I have everything in the program complete EXCEPT that particular input validation.
to convert the input to numeric values i have:
originalRate = Double.Parse(txtValue.Text);
then below that i am stumped, i have been messing around with:
bool isValid = Double.TryParse(txtValue.Text, );
The common compiler runtime error I get while messing around is Input string was not in a correct format. Which i know it is, that is what I am checking for.
I know this is super basic stuff (this is my first C# class). I have searched around on stack overflow and none of the similar solutions make much sense to me at this point. I have been told to use the TryParse method of the decimal class, however feel as though I am using it wrong and incomplete.
Thank you in advance for your help.
Here's how you use double.TryParse()
double d;
bool isValid = Double.TryParse(txtValue.Text, out d);
the MDSN page has some examples.
To parse currency string, you could use the second overload of double.TryParse()
and try something like
double d;
bool isValid = double.TryParse(txtValue.Text, NumberStyles.Currency, CultureInfo.GetCultureInfo("en-US"), out d);
double result;
if (double.TryParse(txtValue.text, out result))
{
// The user typed a valid number.
// Do something with it (it’s in “result”).
}
else
{
// The user typed something invalid.
MessageBox.Show("Please type in a number.");
}

Categories