How can I specify that my decimal.Parse must always expect to receive a string with a '.' like "4.75" no mater what the system settings of the computer are?
I am reading in a file from excel and it gives me value with a '.' and I see that if I run my program on my laptop It throws and error as it expects a ','
I can use:
string tmp1 = tmp[2].Replace('.', ',');
but then obviously if my computer wants a ''. then it will give an error.
What is my best option?
See: Double.Parse
Use this overload to specify an IFormatProvider in your case CultureInfo.InvariantCulture.
var value = double.Parse(tmp[2], CultureInfo.InvariantCulture);
However I would recommend Double.TryParse if you intend to make your process durable.
double value;
if(!double.TryParse(tmp[2],
NumberStyles.None,
CultureInfo.InvariantCulture,
out value))
{
// error handling
}
Use Double.Parse Method (String, IFormatProvider) with CultureInfo.InvariantCulture for parsing.
double d = double.Parse("2.2", CultureInfo.InvariantCulture);
You could use the overload of Decimal.Parse which will allow you to specify a culture:
decimal value = decimal.Parse(tmp[2], CultureInfo.InvariantCulture);
Related
Seeing a strange issue where on some systems the below code steps into the if statement (i.e. it returns true) while in other systems it returns false and steps into the else statement. What environmental conditions or framework version changes am I missing where this was changed? For example .net Fiddle returns true, but my own console apps return false.
DateTime time;
formatText = "";
if (DateTime.TryParse (DateTime.Now.ToString(formatText), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out time))
{
// If TryParseExact Worked
Console.WriteLine ("True: " + time.ToString ());
}
else
{
// If TryParseExact Failed
Console.WriteLine ("Failed to Parse Date");
}
String representations of DateTime are culture specific.
Passing an empty string or null as the format parameter of the ToString overload of DateTime is the same as passing the standard format specifier "G" - from the remarks section of the DateTime.ToString Method (String) msdn page:
If format is null or an empty string, the general format specifier, 'G', is used.
The TryParse overload you are using attempts to parse the DateTime value using the date and time formats available in the IFormatProvider format parameter - InvariantCulture in your case - so when you use TryParse with InvariantCulture, unless your current culture's ShortDatePattern and LongTimePattern properties are the same as in InvariantCulture, the tryParse will fail.
I want to convert a string into int. I have string value like this "45,454,566.00". While typecasting throwing error
Input string was not in a correct format
int GrandTotalInWords = Int32.Parse(grandtotal);//error
grandTotalInWords.InnerHtml = ConvertNumbertoWords(GrandTotalInWords);
First of all, int.Parse uses NumberStyles.Integer which does not includes any thousands and decimal separator styles.
As a second, your CurrentCulture might not use , as a NumberGroupSeparator and/or might not use . as a NumberDecimalSeparator.
Just specify your culture settings and number styles;
int GrandTotalInWords = int.Parse(grandtotal,
NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture);
By the way, if your fraction part is not always zero, that makes your string is not a valid format for an int. In such a case, you might need to parse it to a floating-point type like double as;
double GrandTotalInWords = double.Parse(grandtotal,
NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture);
I get the following error when i try to convert to date time.
String was not recognized as a valid DateTime.
cost.b_date = DateTime.Parse(c_date.Text) ;//c_date.Text = 12/28/2012
Then i try
string date = string.Format("{0:yyyy-MM-dd}",c_date.Text);
cost.b_date = DateTime.Parse(date) ;
but i get the same exception how to fix this problem.
Using string.Format when the input is a string is pointless.
If you know the format of the string, you should use DateTime.ParseExact or DateTime.TryParseExact. For example, for the string you've got, you could use:
DateTime date = DateTime.ParseExact(text, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
You should consider:
Is this user input? If so, use TryParseExact to detect user error more easily without an exception.
Do you definitely know the exact format? If not, using DateTime.TryParse may be more appropriate.
Do you definitely know the culture? If it's not the culture of the current thread, you should specify it explicitly.
Do you have to get the value as text to start with? If you could use an alternative form of input which gives you the value as a DateTime to start with, that would be preferable.
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact(c_date.Text, "d", provider);
Try using DateTime.ParseExact.
DateTime date = DateTime.ParseExact(c_date.Text, "yyyy/MM/dd", null);
I need to convert a String to DateTime format, for this I just tried like
DateTime.ParseExact(DateOfBirth,"MM/dd/yyyy",CultureInfo.InvariantCulture);
it's working fine when I pass the value like 05/30/2012.
But if I try to pass the value as 5/30/2012 its showing error:
String was not recognized as a valid DateTime
To fix this I tried like
DateTime.ParseExact(String.Format("{0:MM/dd/yyyy}", DateOfBirth), "MM/dd/yyyy",
CultureInfo.InvariantCulture);
it's still not working. Here If I try String.Format("{0:MM/dd/yyyy}", DateOfBirth) for the value 5/30/2012 its showing the same format instead of 05/30/2012.
How can I fix this, can anyone help me here...
check this link
string to DateTime conversion in C#
Use M/d/yyyy instead of the format specifier you're using. Using only a single M matches months with leading zeros as well. This is also true for d.
assuming your DateOfBirth string is always separated by slashes, you could try something like this:
string[] dateParts = DateOfBirth.Split('/');
DateTime.ParseExact(string.Format("{0:00}", dateParts[0]) + "/" + string.Format("{0:00}", dateParts[1]) + "/" + string.Format("{0:0000}", dateParts[2]));
I think the issue is the format string can't be recognized since DateOfBirth is not a DateTime object. Thus, you enforce formatting by reformatting the string yourself
There is an overload which might be of your interest
DateTime.ParseExact(DateOfBirth,
new[] { "MM/dd/yyyy", "M/dd/yyyy" },
CultureInfo.InvariantCulture,
DateTimeStyles.None);
This should help you take care of single as well as two digit month part (since 5 is failing for you as the format is MM)
Since you have separators in your string (ie /), you can just do;
DateTime.ParseExact(DateOfBirth,"M/d/yyyy",CultureInfo.InvariantCulture);
That will parse either single or double digit days/months. When you use MM/dd/yyyy, you're requiring them both to be double digit numbers, and that's obviously not what you want in this case.
Try just "d" instead of "MM/dd/yyyy".
So, the statement should be:
var date = DateTime.ParseExact(DateOfBirth, "d", CultureInfo.InvariantCulture);
The documentation for this is here:
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
Edit
Oops, I misread the documentation. It should be "M/d/yyyy".
In case you need to make it culture-independent..
var dateTimeFormat = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentUICulture.Name).DateTimeFormat;
dateTimeFormat.ShortDatePattern =
Regex.Replace(Regex.Replace(dateTimeFormat.ShortDatePattern, "[M]+", "MM"), "[d]+", "dd");
var newDate = date.HasValue ? date.Value.DateTime.ToString("d", dateTimeFormat) : null;
Sounds easy but when I tried to achieve i'm stock about how is the formatter to make this conversion this are some examples of strings that i need to convert to decimal
00.24
48.34
01.24
Does anybody know how can i Accomplish this?? I tried like this
try
{
decimal x = Convert.ToDecimal("00.24", );
//Which formatter do I need to pass??
decimal x = Convert.ToDecimal("00.24", Formatter???);
}
Catch(Exception e)
{
throw new Exception()
}
But It doesn't work because the result it's 24D and i need 0.24D
I suspect your system culture is not English and has different number formatting rules. Try passing the invariant culture as the format provider:
decimal d = Convert.ToDecimal("00.24", CultureInfo.InvariantCulture);
You could also use Decimal.Parse:
decimal d = Decimal.Parse("00.24", CultureInfo.InvariantCulture);
Why not just use Decimal.Parse
decimal x = Decimal.Parse("00.24");
Console.WriteLine(x); // Prints: 00.24
I think Decimal.TryParse should work. More info here.
The result you're getting is because the dot . is tretaed as a group (thousand) separator. the parser simply discards it, and doesn't check if the group sizes are right. So '20.100.200' or '1.2.3.4' would also get parsed as 20100200 and 1234.
This happens on many european cultures, like 'es'
You have to use any culture that doesn't consider a . as a group separator, but as a decimal separator. CultureInfo.InvariantCulture is one of the possible cultures (it has basically the same configuration of en-US).