Exception while converting String to Double C# - c#

I take data from four different pages and different domains.
1- .com
2- .co.uk
3- .ca
4- .co.jp
For all of the above i take number from Html and Convert them to Double using line:
string lowestSellerPrice = (Convert.ToDouble(fbalPrice) +
Convert.ToDouble(fbalsPrice)).ToString();
This works perfectly fine for the first 3 domains but for .co.jp even though there is always a number in fbalPrice and fbalsPrice it is always giving exception :
Input string was not in a correct format
Any suggestion as i have been struggling with this for too long now no result i also tried the try parse solution but no luck.
UPDATE:
See this:

I solved it like this :
The string were like " 1234" and " 111" and i then did Replace(" ",""); . And only number lift this however did not work so i did this:
if (fbalPrice.Contains(" "))
{
fbalPrice = fbalPrice.Remove(0, fbalPrice.IndexOf(" ") + 1).Replace(",","").Trim();
}
if(fbalsPrice.Contains(" "))
{
fbalsPrice = fbalsPrice.Remove(0, fbalsPrice.IndexOf(" ") + 1).Replace(",", "").Trim();
}
And then added them and it worked.

Related

Add double quotes to a list to display in a label

Morning folks,
I have an ASP.Net C# page that pulls in a list of servers from a SQL box and displays the list of servers in a label. ("srv1,srv2,srv3"). I need to add double quotes around each of the servers names. ("srv1","srv2","srv3",)
Any help would be greatly appreached.
If you have string
string str = "srv1,srv2,srv3";
Then you can simply do
str = "\"" + str.Replace(",", "\",\"") + "\"";
Now str contains "srv1","srv2","srv3"
As far as I can understand, you are trying to use double quotes in a string.
If you want to use such,
you can use escape character:
("\"srv1\",\"srv2\",\"srv3\"",)
for the sake of simplicity, you can even convert it to a function:
private string quoteString(string serverName){
return "\"" + serverName + "\"";
}
Also, if you have already "srv1,srv2,srv3" format, find ',' characters in the string and add " before and after comma. Also, notice that you should add to first index and last index ".

String comparison fails even when visually checked

I added a function to my application recently that reads a date from a downloaded file and finds the difference in days between current date and the date from the file. When done, it is displayed in a label in one of my forums.
There is an exception: if the string in the file equals "Lifetime", it should not process it as a date and follow alternate logic. But when I try to check if the string is "Lifetime", it does not return true, even if the string = "Lifetime".
EDIT: I fixed the FormatException with help from Nisarg. Now, my labels aren't changing to the values. This is the problem.
EDIT2: I feel stupid. I found out that I was initiating Main twice in one function, then using main1 to switch between forms and main to set the labels.
This is why the labels weren't working right. Thanks Nisarg and all other contributors.
Code example:
string subScript = File.ReadAllText(Path.GetTempPath() + txtUsername.Text + ".txt");
Main main = new Main();
double dSubLeft;
main.dateLabel.Text = subScript;
if (subScript == "Lifetime") // it bypasses this, apparently blank
{
main.daysLeftLabel.Text = "Expires: Never";
}
if (subScript != "Lifetime") //Goes here and throws error saying subScript is not valid DateTime
{
dSubLeft = Math.Round(Convert.ToDouble(Convert.ToString(((Convert.ToDateTime(subScript)) - DateTime.Now).TotalDays)));
string sSubLeft = Convert.ToString(dSubLeft);
main.daysLeftLabel.Text = "Expires: " + sSubLeft + " Days";
}
While using files you often get trailing blank spaces or newline characters. Try trimming the string before comparing it to Lifetime:
subScript = subScript.Trim().Trim(Environment.NewLine.ToCharArray());
Another (less likely) problem could be with the comparison itself. In C# the comparison in case-sensitive. So if you're comparing lifetime with Lifetime they are considered unequal. You should rather use case-insensitive comparison:
if(string.Equals(subScript, "Lifetime", StringComparer.OrdinalIgnoreCase))
OR
if(subScript.ToLower() == "lifetime")
You could also check if the subScript you are getting from the file is a valid date or not using DateTime.TryParse.
string subScript = File.ReadAllText(Path.GetTempPath() + txtUsername.Text + ".txt");
Main main = new Main();
double dSubLeft;
main.dateLabel.Text = subScript;
DateTime subScriptDate;
if(!DateTime.TryParse(subScript, out subScriptDate))
{
main.daysLeftLabel.Text = "Expires: Never";
}
else //Goes here and throws error saying subScript is not valid DateTime
{
dSubLeft = Math.Round(Convert.ToDouble(Convert.ToString((subScriptDate - DateTime.Now).TotalDays)));
string sSubLeft = Convert.ToString(dSubLeft);
main.daysLeftLabel.Text = "Expires: " + sSubLeft + " Days";
}
I think it is because main is the starting point of a program in C#, make another methodname if you donĀ“t want it to reset things from where the program is supposed to start from
That is my guess only, make a breakpoint in the beginning of your code and check through what info you get from each row in the code
Almost certainly, the actual content of the string is not actually the string "Lifetime". Probably because of white-space on either side. Try trimming.
Relevant edit:
if (subscript.Trim() == "Lifetime")
{
main.daysLeftLabel.Text = "Expires: Never";
}
else // don't retest for the opposite condition
{
...
As you can see, this thing is awfully fragile, because the string could still be many things that aren't a valid DateTime. Smells like homework, but there you go...
i think you should use
if(string.Equals(subScript, "Lifetime", StringComparer.OrdinalIgnoreCase))
{
//statement
}
else
{
//statement
}

How to get rid of unwanted spaces after using ToString() in C#?

This might be a problem with Session and not ToString(), I'm not sure.
I have two .aspx pages and I want to pass an IP address from a datatable from one page to the other. When I do this, spaces get added that I don't want. The simple version of the code is this:
first .aspx page
int num = DropDownList1.SelectedIndex;
DataView tempDV = SqlDataSource2.Select(DataSourceSelectArguments.Empty) as DataView;
Session["camera"] = tempDV.Table.Rows[num].ItemArray[2];
Response.Redirect("test.aspx");
test.aspx page
string ipCamAdd = Session["camera"].ToString();
TextBox1.Text = "http://" + ipCamAdd + "/jpg/image.jpg?resolution=320x240";
what I want to print is
http ://ipadd/jpg/image.jpg?resolution=320x240
but what prints out is
http//ipaddress /jpg/image.jpg?resolution=320x240
how can I fix this?
Also, I asked this question hoping someone could tell me why this is happening as well. Sorry for the mistake.
Try this:
string ipCamAdd = Session["camera"].Trim().ToString();
For the valid concern, Session["camera"] could be null, add function such as the following to your code
static string ToSafeString(string theVal)
{
string theAns;
theAns = (theVal==null ? "" : theVal);
return theAns;
}
Then use:
string ipCamAdd = Session["camera"].ToSafeString().Trim();
You can use string.Replace if you just want to get rid of the spaces:
TextBox1.Text = "http://" + (ipCamAdd ?? "").Replace(" ", "") + "/jpg/image.jpg?resolution=320x240";
Trim the result before setting to session.
Session["camera"] = tempDV.Table.Rows[num].ItemArray[2].Trim();
Seems In SQL your data type is char(*) if you convert the data type to varchar and re enter data, you wont get any additional spaces

int.Parse of "8" fails. int.Parse always requires CultureInfo.InvariantCulture?

We develop an established software which works fine on all known computers except one. The problem is to parse strings that begin with "8". It seems like "8" in the beginning of a string is a reserved character.
Parsing:
int.Parse("8") -> Exception message: Input string was not in a correct format.
int.Parse("80") -> 0
int.Parse("88") -> 8
int.Parse("8100") -> 100
CurrentCulture: sv-SE
CurrentUICulture: en-US
The problem is solved using int.Parse("8", CultureInfo.InvariantCulture). However, it would be nice to know the source of the problem.
Question: Why do we get this behaviour of "8" if we don't specify invariant culture?
Additional information:
I did send a small program to my client achieve the result above:
private int ParseInt(string s)
{
int parsedInt = -1000;
try
{
parsedInt = int.Parse(s);
textBoxMessage.Text = "Success: " + parsedInt;
}
catch (Exception ex)
{
textBoxMessage.Text =
string.Format("Error parsing string: '{0}'", s) + Environment.NewLine +
"Exception message: " + ex.Message;
}
textBoxMessage.Text += Environment.NewLine + Environment.NewLine +
"CurrentCulture: " + Thread.CurrentThread.CurrentCulture.Name + "\r\n" +
"CurrentUICulture: " + Thread.CurrentThread.CurrentUICulture.Name + "\r\n";
return parsedInt;
}
Update
I stumbled across this link, a bug in the microsoft connect database:
https://connect.microsoft.com/VisualStudio/feedback/details/253265/int32-parse-fails-to-convert-the-string-0-zero-on-some-systems
It seems like there's an issue with similiar symptoms, but no real root cause. If anyone could elaborate on this I would be grateful!
For the sv-SE culture 8 represents CurrencyNegativePattern and that's why you're getting the error you describe.
You can check this by running the following example:
var ci = new CultureInfo("sv-SE");
var nfi = (NumberFormatInfo)ci.GetFormat(typeof(NumberFormatInfo));
Console.WriteLine(nfi.CurrencyNegativePattern);
Console.WriteLine(nfi.CurrencyPositivePattern);
This will output:
// 8
// 3
You can explicitly say that you are parsing an integer and not a currency by using the Parse overload that accepts a NumberStyles enumeration.
Int32.Parse("8", NumberStyles.Integer, new CultureInfo("sv-SE"));
This time since you are specifying that you're parsing an integer no error will occur.
However, IIRC the Int32.Parse should interpret the input as an integer by default, so why you're getting to the error with that sample code is beyond me.
Update:
From the information you recently added it seems that you should make sure that the problem is not external. This is, if the user for example changed the positive sign setting of the windows locale to 8 it would be normal and make perfect sense for you to get the error you are obtaining. It would be just like setting the + as the positive sign and then trying to parse it:
var ci = new CultureInfo("sv-SE");
var nfi = (NumberFormatInfo)ci.GetFormat(typeof(NumberFormatInfo));
nfi.PositiveSign = "+";
Int32.Parse("+", nfi); // This will throw
Ask the user for it's locale registry settings like indicated in the Connect issue and check that they are what you would expect.
Side note: Welcome to SO and by the way next time you need to add further information to your question you should edit it instead of providing it in an answer.

String concatenation doesn't seem to work in C#

I don't know what is wrong with the following string:
"Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " + System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")"
I can't get the concatenated string. I am getting Report(29-Dec-2009. That's all and
the rest gets left out from the string.
What is the reason?
Try this:
string filename =
String.Format(
"Report({0:dd-MMM-yyyy} to {1:dd-MMM-yyyy})",
System.DateTime.Now, System.DateTime.Now.AddMonths(-1));
EDIT: Since in your download box you got your filename broken in first whitespace, you could to try ONE of these:
filename = HttpUtility.UrlEncode(filename); // OR
filename = """" + filename + """";
Seems some browsers doesn't handles whitespaces very nicely: Filenames with spaces are truncated upon download. Please check it you can to download other filenames with whitespace in other sites.
You need to assign it to something:
string s = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " + System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")"
Update: I just saw your update to the question. How are you displaying the string? I'm guessing that you are displaying it in a GUI and the label is too short to display the complete text.
Try this:
string newstring =
string.Format(
"Report ({0} to {1})",
System.DateTime.Now.ToString("dd-MMM-yyyy"),
System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy")
);
What are you assigning the result to? It would be easier to read the code if you used string.Format
You are not assigning the concatenated result to anything, so can't use it:
string myConcatenated = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + ")";
Using this code...
string test = "Report(" + System.DateTime.Now.ToString("dd-MMM-yyyy") + " to " +
System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy") + ")";
I saw the following result.
Report(29-Dec-2009 to 29-Nov-2009)
It could be that the string is being truncated later on. Make sure that you set a breakpoint right after this code is run and check the value of the variable to which it is assigned (test in my case).
If, as in your previous question, you are using this value to create a file, it may be that it's the space before "to" that is causing the problem. Try to use:
"Report("
+ System.DateTime.Now.ToString("dd-MMM-yyyy")
+ "To"
+ System.DateTime.Now.AddMonths(-1).ToString("dd-MMM-yyyy")
+ ")"
instead and see if that fixes it.
If that does fix it, you'll probably need to either figure out how to quote the entire file name so it's not treated as the three separate arguments, "Report(29-Dec-2009", "to" and "29-Nov-2009)". Or simply leave your reports names without spaces.
I'd choose the latter but then I'm fundamentally opposed to spaces in filenames - they make simple scripts so much harder to write :-)

Categories