System.FormatException when parsing String to double - c#

the Code worked fine in Unity. Now I'm using the samecode in a console Project and im getting a System.FormatException exception.
The code is:
private double ConvertToNumber(string number)
{
return double.Parse(number, numberStyle);
}
parameter when calling are:
number = "3.138924e-002"
numberStyle = NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign
Does anyone see the Error, or knows what might caus this?

The exception is thrown because the string you are providing cannot be converted to a number using the format you specified and your own current cultrue. The latter is implict unless you specify it.
If you are reading this value from a database, you should use the invariant culture (i.e. a culture designed to persist numbers and dates in a consistent way in whatever place you need, except user interfaces).
Your code becomes:
return double.Parse(number, numberStyle, System.Globalization.CultureInfo.InvariantCulture);
Instead, if you need a specific culture, you need to pass the correct culture in place of the invariant one.

#Selvin was right about CultureInfo.InvariantCulture adding it as a param fixed the error.
return double.Parse(number, numberStyle, CultureInfo.InvariantCulture);

Related

DateTime.TryParse fails for one user

I need to parse dates in my program, but it fails on the machine of one user (in denmark). It works for his colleagues who all has the same settings as far as I can tell.
The code looks as follows:
DateTime result;
if (DateTime.TryParse(InputBox.Text, out result))
YyyymmddField.Text = result.ToString("yyyyMMdd");
else
YyyymmddField.Text = "(invalid)";
CurrentCulture is da-DK and his configured format is: yyyy.MM.dd. The date string I want to parse is 2015.07.14.
This works on our machines here (in sweden) regardless of current culture. It also works for his colleagues, but not for him.
We have hundreds of users worldwide and as far as we know, his is the only computer that fails.
Could something other than the current CultureInfo affect how TryParse operates?
This works on our machines here (in sweden) regardless of current
culture
No. There is no such a thing. If you use DateTime.TryParse without any IFormatProvider, it will use the CurrentCulture settings of the current machine.
From documentation;
The string s is parsed using formatting information in the current
DateTimeFormatInfo object, which is supplied implicitly by the current
thread culture.
I'm using .NET Framework 4.5 and there are only 7 culture inside of AllCultures that doesn't have this as standard date and time format. If you won't/can't tell us what is your other colleague's CurrentCulture, I would assume he will use one of these from my perspective.
ar
bn
ml
ar-SA
bn-IN
ml-IN
bn-BD
Instead of that confusion, you can use InvariantCulture is your string has a stable format like yyyy.MM.dd instead of hoping his CurrentCulture settings will parse it or not.
use CultureInfo.InvariantCulture
DateTime result;
if (DateTime.TryParse(InputBox.Text, out result))
YyyymmddField.Text = result.ToString("yyyyMMdd",CultureInfo.InvariantCulture);
else
YyyymmddField.Text = "(invalid)";
In principle, it can be a good idea to have reusable methods (such as extension methods) for parsing DateTimes and numerics, which use the invariant culture.

Converting string to decimal: how to handle the decimal separator in different cultures

I need to write decimal value to ms access database, but i have a problem with conversion values to decimal in different cultures. Have a values from file, which separates by commma. I try:
public decimal CSingleCulture (string str)
{
string sep = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
string s = str.Replace(",", sep);
return decimal.Parse(s);
}
if NumberDecimalSeparator = "." then work is good, but if NumberDecimalSeparator = "," problems begin... decimal.Parse(s) always return vlaues separates by dot. In this situation, when inserted into a database error occurs.
The recommended way to deal with this is to store the value as a number rather than a string. Both in the database and in your program. When you do that, your current problem simply never arises.
The only time you deal with numbers in string format is when you display them, or accept user input. In those scenarios you can use the user's culture settings to let them see and use their preferred separator.
Should you ever need to convert between string and number for persistence then you must use culture invariant conversion. This appears to be where you are falling down. I suspect that the file you read has no well-defined format. Make sure that when you read and write the file you use CultureInfo.InvariantCulture. If the file does have a well-defined format that differs from the invariant culture, then use an appropriate specific CultureInfo.
Can't actually understand what is it you're trying to accomplish, and I have to agree with the other answer. But one other thing that's good to know is you can use invariant culture like so:
double.Parse("15.0", CultureInfo.InvariantCulture)
This will always expect dot character to delimit your decimal digits regardless of what is set in current thread's culture.

System.Convert.ToSingle(value) always throws FormatException

I have several strings that I need to convert to float. When I try to do so, using System.Convert.ToSingle(MyString), I always get a FormatException.
I have tried even creating strings like "12.123", to make sure the numbers are okay, but again I got the exception. My question is, what is the correct format then? In what format should the number in string be?
Example of one of many strings I will convert: 50.105128
It could be down to your system's culture which may be set to using a , as the separator. Setting the format to InvariantCulture will use a . for the separator.
Convert.ToSingle("12.123", CultureInfo.InvariantCulture)
It depends on culture, but you can use invariant in this way:
Convert.ToSingle("0", System.Globalization.CultureInfo.InvariantCulture);
Convert.ToSingle is culture-sensitive. In culture installed on your machine, decimal separator might be different from comma, and number may look like 50,105128
Use this overload instead, which allows to specify culture:
public static float ToSingle(
Object value,
IFormatProvider provider
)

Convert number in textbox to float C#

I have textbox that accept numbers. Those numbers will be saved in database.
When I enter number like 2,35 and convert to float and send to database I get error because database accept only number with dot, e.g. 2.35
float num = float.Parse(textBox1.Text);
num is still 2,25
How to manage that? I've tried with CultureInfo.InvariantCulture but I never get what I want
You can try the following:
float.Parse(textBox1.Text.Trim(), CultureInfo.InvariantCulture.NumberFormat);
I hope this would've solved the issue.
The easiest way is to replace ',' with '.' in like:
float num = float.Parse(textBox1.Text);
string stringValue = num.ToString().Replace(',', '.');
Then send "stringValue" to database.
I hope that helps you.
use this:
CultureInfo.CreateSpecificCulture("en-US");
I have same problem back then and it solved by code above
num is 2,25 because it's shown to you in your culture. It will be passed correctly to the database, provided you use the usual mechanisms (i.e. prepared statements with parameters). If you insist on manually gluing together SQL, then by all means use InvariantCulture to format the number, but generally, please don't.
This is a common globalization issue. What you have to define is a single culture in which to store the data itself, since you are storing it as a string value. Then, do ALL your data input and handling using that culture. In our code, we have several blocks that look similar to this in order to handle multi-cultural math and data display:
//save current culture and set to english
CultureInfo current = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
//Do Math and Data things
//restore original culture
System.Threading.Thread.CurrentThread.CurrentCulture = current;
This way you can make sure that all the data is handled and stored the same way, regardless of the culture being use to generate or display the data.
Edit
To do the data save, and converting the number to a string, you would do things exactly the same way. While you have the current threads CultureInfo setting as "en-US", the .ToString() methods from all the numbers will use "." instead of "," for the decimal point. The other way to do it is specify a format provider when calling .ToString().
decimalNumber.ToString(new CultureInfo("en-US"));
This specifies that when you convert the number to a string, use the NumberFormat from the provided culture.

Can't parse text to Decimal

In Form_load I have
txtAlteFonduri.Text = "5,00";
txtFReparatii.Text = "15,00";
txtFRulment.Text = "20,00";
and in another function I want to parse text as decimal
decimal alteFonduri = Decimal.Parse(txtAlteFonduri.Text);
decimal fondRulment = Decimal.Parse(txtFRulment.Text);
decimal fondRepar = Decimal.Parse(txtFReparatii.Text);
but I have an error in the second line
Input string was not in a correct format.
You need to specifically add the number format. For your examples above, the following should work:
decimal alteFonduri = Decimal.Parse(txtAlteFonduri.Text, CultureInfo.GetCulture("de-DE"));
Otherwise, the system's culture information is used.
You are using a different culture to what decimal.Parse() is expecting (it expects the decimal point '.' but you provide a comma. Using the correct culture should correctly parse the strings, although I can run your code without having any errors...
You can use Decimal.Parse(variable, CultureInfo.GetCultureInfo("Culture-Name"));
You have to use this overload of Decimal.Parse and supply a IFormatProvider matching the culture of your input. You should also consider using one of the Decimal.TryParse methods for better error handling.

Categories