double.Parse throw a System.FormatException - c#

I am trying to parse some string to a double value, using this parse method overload:
double.Parse("198.222213745118", CultureInfo.CurrentUICulture);
the CultureInfo.CurrentUICulture is fr-FR.
but this is throwing an exception of type FormatException.
What can be the reason?

French (i.e. fr-FR) use a comma to denote the start of the decimal part, not a period. They use a period to separate thousands.

I know this question is old but my answer might help someone else.
So this is the answer:
double.Parse("198.222213745118", System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.NumberFormatInfo.InvariantInfo);
instead of
double.Parse("198.222213745118", CultureInfo.CurrentUICulture);

I suggest using the Double.TryParse rather than the .Parse as it is safer to use and makes sure you dont get any exception on parsing.
Here is a Code for you to use,
double answer = -1;
Double.TryParse("Value", out answer);
Now all you have to do is do a conditional statement that'll check if it indeed parsed' the string.

Related

C#: Scientific notation String to Int64 conversion failing

I'm getting an exception when trying to parse a number that is in scientific notation. Looking at other posts on how to do it, and I can't tell what I'm doing any differently than those.
I've tried the following:
System.Convert.ToInt64("1.0206e+06");
System.Convert.ToInt64("1.0206E+06"); // Uppercase 'E'
These result in a FormatException: Input string was not in the correct format.
I tried these:
Int64.Parse("1.0206e+06", System.Globalization.NumberStyles.Any);
Int64.Parse("1.0206e+06", System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture);
Int64.Parse("1.0206e+06", System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);
These all result in an OverflowException: Value was too large or too small.
Also tried with Int32.Parse and got the same exception and message:
(long)Int32.Parse(str, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture);
Using Decimal.Parse works with the same string and parameters passed to it:
(long)Decimal.Parse(str, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture);
This answer suggests using this:
Double.Parse("1.234567E-06", System.Globalization.NumberStyles.Float);
Which is similar to my last example, I just accept all number styles, and that answer used a negative exponent. In fact, I fed that exact string into my examples and I still get the same exceptions.
Not sure if it matters, but I'm using Mono C#, the version that comes with Unity.
Here's the C# source file: https://github.com/Unity-Technologies/mono/blob/unity-staging/mcs/class/corlib/System/Int64.cs. The exception is thrown on line 469 and doesn't provide me a call stack before that point. But I'm guessing the exception is created on line 355 or 372 since those match the exception type and message I'm being shown.
I'm going to assume that this is a bug with the version of Mono C# I'm using, which comes with Unity 5.5.x or earlier. Their repository can be found here.
Their implementation of Int64.Parse does not even check for the NumberStyles.AllowExponents flag, or handle exponents in any way. So it's going to fail when it finds the + symbol in the string. Basically, Int64.Parse when using Unity does not support exponents.
Mono's Int32.Parse does seem to look for exponents, but still causes an OverflowException with all exponents that I give it.
Decimal.Parse actually does work with the same parameters as the other two, which suggests there was nothing wrong with the string or parameters, but it's just a bug in their other Parse methods. Decimal's parsing is completely different from how the Int parsing is being done, so that may explain why it works and the others don't.

Restrict value on decimal TryParse

I have following code:
Decimal.TryParse("1.0e-50", NumberStyles.Float,CultureInfo.CurrentCulture.NumberFormat, out val)
I want to restrict it to e-45. Is there a way to do this without using regular expressions? I googled it but only best way i got was regex.
You should really just parse it as a decimal without bounds checking it, and then check the min/max values after you've parsed it into a numeric value. Trying to do the bounds checking on the string, before parsing it, is just asking for trouble; it'll be way more work, and more error prone.
Parse the value first and just compare it with a min/max value afterwards because there is no better way than regex to check how big the decimal value contained by the string is. All in all, parsing is much cleaner, efficient and I also would guess that it is faster.

C# - Force String.Format to use decimals and NEVER commas

Basically I'm realizing that my application is using commas instead of decimals, and i NEVER want to allow this. Anyone know how I can correct? I can't find one thing via google that is to force decimals, it's all about forcing commas.
return String.Format("{0}f, {1}f, {2}f, {3}f, {4}f, {5}f, {6}f, {7}f, {8}f, {9}f, {10}f, {11}f, {12}f, {13}f, {14}f, {15}f", M.M11, M.M12, M.M13, M.M14, M.M21, M.M22, M.M23, M.M24, M.M31, M.M32, M.M33, M.M34, M.OffsetX, M.OffsetY, M.OffsetZ, M.M44);
You can use the other overload:
return String.Format(
CultureInfo.InvariantCulture // <<== That's the magic
, "{0}f, {1}f, {2}f, {3}f, {4}f, {5}f, {6}f, {7}f, {8}f, {9}f, {10}f, {11}f, {12}f, {13}f, {14}f, {15}f"
, M.M11, M.M12, M.M13, M.M14, M.M21, M.M22, M.M23, M.M24, M.M31, M.M32, M.M33, M.M34, M.OffsetX, M.OffsetY, M.OffsetZ, M.M44
);
This way of calling ensures that the invariant culture is being passed as the format provider to the String.Format, ensuring that you get dots for numbers, dollars for currency symbols, English for names of the months and days, and so on.
Try setting the culture to US English for the String.Format function:
String.Format(new CultureInfo("en-US"), "{0}f, {1}f, {2}f", etc)

Replacing backslash in a string

I am having a few problems with trying to replace backslashes in a date string on C# .net.
So far I am using:
string.Replace(#"\","-")
but it hasnt done the replacement. Could anyone please help?
string.Replace does not modify the string itself but returns a new string, which most likely you are throwing away. Do this instead:
myString= myString.Replace(#"\","-");
On a side note, this kind of operation is usually seen in code that manually mucks around with formatted date strings. Most of the time there is a better way to do what you want (which is?) than things like this.
as all of them saying you need to take value back in the variable.
so it should be
val1= val1.Replace(#"\","-");
Or
val1= val1.Replace("\\","-");
but not only .. below one will not work
val1.Replace(#"\","-");
Use it this way.
oldstring = oldstring.Replace(#"\","-");
Look for String.Replace return type.
Its a function which returns a corrected string. If it would have simply changed old string then it would had a void return type.
You could also use:
myString = myString.Replace('\\', '-'));
but just letting you know, date slashes are usually forward ones /, and not backslashes \.
As suggested by others that String.Replace doesn't update the original string object but it returns a new string instead.
myString= myString.Replace(#"\","-");
It's worthwhile for you to understand that string is immutable in C# basically to make it thread-safe. More details about strings and why they are immutable please see links here and here

C# - failed parse exception?

I am writing a program in C#, and I want to catch exceptions caused by converting "" (null) to int. What is the exception's name?
EDIT:
I'm not sure I can show the full code... But I'm sure you don't need the full code, so:
int num1 = Int32.Parse(number1.Text);
int num2 = Int32.Parse(number2.Text);
If you can avoid it, do not code by exception!
The exception name you are looking for is called a FormatException.
However, it would be smarter to first do a TryParse on the object you are attempting to parse, e.g.
int value;
if(!int.TryParse("1", out value))
{
// You caught it without throwing an exception.
}
You are going to get a FormatException if a parse fails. Why not use int.TryParse instead?
As a side note, a simple way to find out the exception is to run it. When you encounter the error, it'll give you the exception name.
Let's have a look at the documentation (which is a much cleaner solution that "trying it out"):
public static int Parse(string s)
[...]
Exceptions:
ArgumentNullException: s is null.
FormatException: s is not in the correct format.
This should answer your question. As others have already mentioned, maybe you are asking the wrong question and want to use Int32.TryParse instead.
Depends on what you're using to do the conversion. For example, int.Parse will throw ArgumentNullException, FormatException, or OverflowException. Odds are it's ArgumentNullException you're looking for, but if that's an empty string rather than a null reference, it's probably going to be FormatException
When the exception fires you can see it's type. The smart thing to do is handle that case and display a graceful message to your user if possible.
You're probably looking to get a System.InvalidCastException, although I think that'll depend on how you try to perform the conversion.
That said, wouldn't it be quicker/easier to simply write the code and try it yourself? Particularly as you haven't specified how you'll be performing the conversion.
Just try it. This code:
int.Parse("");
Throws a FormatException.
Exceptions are expensive. You should use int.TryParse. It will return the boolean false if the conversion fails.
Convert.ToInt32 does not throw a format exception ("input string is not in the correct format") on a null string. You can use that if it is acceptable for the result to be a 0 for a null string. (still pukes on empty string though)
string s = null;
int i = Convert.ToInt32(s);
But if you expect a number to be in the box, you should either use TryParse (as was suggested) or a Validator of some kind to inform the user that they need to enter a number.

Categories