How to parse string to double in C# - c#

My c.ShareWhite is a string, but i cant convert this to double with using Double.Parse
double a = Double.Parse(c.ShareWhite.ToString());
error:
nhandled exception. System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Double.Parse(String s)
can someone tell ne how to parse string to double?

First of all, I recommend using TryParse() method which is implemented for type wrapper classes like Int32, Double, ...etc.
Docs here: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=netcore-3.1
Basically it returns a bool indicating if the parse was succesfull instead of breaking the program with an exception and places the result of the conversion into the given variable.
double d;
bool res = Double.TryParse(c.ShareWhite, out d);
You have to make sure your string is a valid double and not anything else nor an empty string because both cases can give you format exception if you use a simple Parse method.
You should pick a breakpoint in your IDE before the step where you try to parse (https://learn.microsoft.com/en-us/visualstudio/debugger/using-breakpoints?view=vs-2019) and check what kind of string value is passed to the (Try)Parse method.
It can be the some steps before or complelety from the beginning you are working with a bad value.

Related

How to convert int to decimal in BizTalk orchestration xpath?

How to convert int to decimal in Orchestration using xpath ? My QuantityReturned field is type integer in my schema when it calls the webservice it converts to decimal and call the webservice. Below is the xpath query for QuantityReturned.
QuantityReturned=xpath(OrderReturnMessage,
"number(/*[local-name()='QuantityReturned' and namespace-uri()=''])");
wSReturnSuccess = WebServiceHelper.CreateReturnAAAWS
(System.Convert.ToDecimal(QuantityReturned));
When tried with number function in xpath query, throw error that input string is not correct format.
It's very likely that your xpath is incorrect and returning a value which cannot be converted to decimal.
Can you evaluate your xpath against the message xml and see what is actually returned? Your current expression resolves to the value of an unqualified, root-level element called QuantityReturned.
Unless your message xml matches this, your xpath will likely return empty string.
In addition to Tom Redfern's answer, which is likely the root cause, I would recommend refactoring this into a call in an external assembly, such as:
public static decimal StringToDecimal(string s)
{
if (string.IsNullOrWhiteSpace(s))
{
// log error, throw exception, or just return a default value if acceptable
}
decimal d;
if (decimal.TryParse(s, out d))
{
return d;
}
else
{
// appropriately log errors and/or throw a more meaningful exception
}
}
You could also look into some of the NumberStyles options that the other overload of TryParse offers.
You could do this in an orchestration, but if this method becomes any more complex it's going to start looking really ugly in the expression editor - even as it is it will look a little ugly in the expression editor.

Checking empty text boxes which convert strings to integers using "int.Parse" method in C#

How do I check the empty check boxes which convert strings to integers using "int.Parse" in C#?
If I try to pass blank text boxes, visual studio gives me this error - "Input string was not in a correct format."
I already read some questions on stackoverflow which address the same issue, but I know that various people use various methods to do the same task. So I would like to know them as well. Please start with the simplest way you know first.
int multiplyBy;
if(int.TryParse(textBox3.Text, out multiplyBy)) {
//success
} else {
//string was not in correct format
}
The int.TryParse(string s, out int result) method trys to parse the string, but throws no exception if the format is wrong, it returns a bool indicating if the format was valid. The out int result parameter is the int wich should get the value.
Use Int32.TryParse to verify that the value in the text box is a valid integer
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
You can check if the textbox has a value with:
string.IsNullOrEmpty(textbox.Text)
if you want it in single line of code
vb.net
int i = If(String.IsNullOrEmpty(TextBox1.Text), 0, Int32.Parse(TextBox1.Text))
c#
int i = (String.IsNullOrEmpty(TextBox1.Text)) ?? 0: Int32.Parse(TextBox1.Text)
Instead of directly parsing string representation into integer, check whether it is able to convert in integer. .NET has TryParse method of integer which tries to convert the string representation into int , and returns the bool value indicates whether the conversion succeeded. And if succeeded, stores the parsed value in second parameter of TryParse function which is of out type.
Note: TryParse method does not throw an exception if the conversion fails. It simply returns false indicates that conversion is got failed.
Ref : http://msdn.microsoft.com/en-us/library/f02979c7.aspx
Why don't you just catch the exception
try
{
int multiplyBy = int.Parse(textBox3.Text);
} catch(Exception){}
You can also catch(FormateException) if you like.
Hope this helps!

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.");
}

Input string was in incorrect format error when saving to database

In SQL Server I have a db column named AppZip with type int. I have a textbox with a 5 digit zip code. When i try to save I get an error "Input string was in incorrect format." I'm confused. I'm converting the string representation of "12345" to int type, how is it the wrong format for the database? Here's my code.
q.AppZip =Convert.ToInt32(txtAppZip.Text);
(I'm using linq to sql...)
EDIT: It was because I didn't stop the method that populates the field on page load from executing on post back.
The exception is being thrown by the Convert.ToInt32(). Check whether the Text property is in correct format and Trim() the property before you pass it to Convert.ToInt32().
string appZipText = txtAppZip.Text.Trim();
if (!string.IsNullOrEmpty(appZipText))
{
q.AppZip = Convert.ToInt32(appZipText);
}
Additionally, you can also use Int32.TryParse() to check the validity of the string before you convert.
int appZip;
string appZipText = txtAppZip.Text.Trim();
if(!string.IsNullOrEmpty(appZipText) &&
Int32.TryParse(appZipText.Trim(),NumberStyles.Integer,CultureInfo.CurrentCulture, out appZip))
{
// Valid format
// Use or assign converted value
q.AppZip = appZip;
}
else
{
// Cannot convert to Int32
}
More information
Int32.Parse Method (String, NumberStyles, IFormatProvider)
Convert.ToInt32 Method (String)
Check the mappings of all the columns in your table definition. It could be one of the other columns in the table throwing the error. Run up SQL Profiler to check the SQL that is generated.
The only way to raise the FormatException is concating some unconvertible character to the original string.
Make sure you didnt type anything char by mistake and try again, thats the only reasonable explanation i can see now

Categories