Situation - The thread culture in my web app has been set to 'es' (Spanish)
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("es");
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("es");
The string value is "0.1"
For the following expression,
var value = "0.1"
provider = CultureInfo.CreateSpecificCulture("en-US")
double.TryParse(value.ToString(), NumberStyles.Any, provider, out number)
number returns 1.0. Which makes me think that it is picking the culture info from the thread. Not the one I provide.
The following unit test passes (as expected).
var numberInEnUS = "0.1";
var spanishCulture = CultureInfo.CreateSpecificCulture("es");
culture = new CultureInfo("en-US", false);
Thread.CurrentThread.CurrentCulture = spanishCulture;
Thread.CurrentThread.CurrentUICulture = spanishCulture;
double number;
double.TryParse(numberInEnUs, NumberStyles.Any, culture, out number);
Assert.AreEqual(0.1, number);
So, the question is why does double.TryParse fail in my application? Theoretically, 0.1 for Spanish is 1 (Separator for spanish is a decimal point '.'). However, number 1000.0 does not get converted to 10000. So, it seems that it fails only for 0.1
Any explanation is highly appreciated!
You say "0.1" is number in spanish. Actually not, It is numberInEnglish or something else
var numberInSpanish = "0.1";//this is number in english culture
It should be
var numberInSpanish = "0,1";//<--Note 0,1
NumberDecimalSeparator for spanish is ,. Parse 0,1 you'll get expected result.
var numberInSpanish = "0,1";
var spanishCulture = CultureInfo.CreateSpecificCulture("es");
var culture = new CultureInfo("en-US", false);
Thread.CurrentThread.CurrentCulture = spanishCulture;
Thread.CurrentThread.CurrentUICulture = spanishCulture;
double number;
double.TryParse(numberInSpanish, NumberStyles.Any, spanishCulture, out number);
Here number is correctly parsed to "0.1"
Your problem is in the mixture of decimal and thousand separators, namely:
'.' - thousand separator in "es" culture, when parsing, will be ignored (e.g. 1.000,0 == 1000,0)
',' - decimal deparator in "es" culture, separates integer and fractional parts
You can easily convince yourself:
var spanishCulture = CultureInfo.CreateSpecificCulture("es");
Char dS = spanishCulture.NumberFormat.NumberDecimalSeparator; // <- ','
Char tS = spanishCulture.NumberFormat.NumberGroupSeparator; // <- '.'
So, in your case the string "0.1" will be converted into 1.0 double since '.' as
being a thousand separator in es culture will be ignored.
You can do either:
Use Invariant culture instead of "es" one:
double.TryParse(numberInNeutral, NumberStyles.Any, CultureInfo.InvariantCulture, out number);
Or use actual Spanish number representation:
var numberInSpanish = "0,1";
double.TryParse(numberInSpanish, NumberStyles.Any, culture, out number);
I finally was able to identify what was wrong. The issue was not with the TryParse() function but the ToString() function.
The value was actually a Double type, not a string as I mentioned above. (My bad, I thought it was not relevant). I was actually doing a value.ToString(). This is where it uses the thread culture and changes the value.
So, if the value was 0.1, the value.ToString() changes it to "0,1". It automatically changes the decimal character based on the Thread culture. The TryParse then uses the en-US culture and convert "0,1" to 1.
To fix it, use Convert.ToString instead and pass in the culture info.
At the end, it was just a silly mistake.
LessonLearnt - Be careful when using ToString() in globalized applications!
Related
This is my code:
string myValue = "0,203";
decimal.TryParse(myValue, NumberStyles.Any, CultureInfo.CurrentCulture, out myValueAsDecimal;
...
myValueAsDecimal is 0.203 now
Is it possible that myValueAsDecimal has 0,203 after TryParse or the internal representation of decimal is always 0.203 and I need to format GUI output if I need 0,203?
Is it possible that myValueAsDecimal has 0,203 after TryParse
No. It's just a number - it has no concept of a text format. To think about it another way with a simpler type, consider these two lines of code:
int x = 0x100;
int y = 256;
Are those two values the same? Yes, they represent the same number. If you convert the values of x and y to strings, by default they will both end up as "256" - but they could both end up as "100" if you request a hex representation.
It's important to distinguish between the real value of a variable and a textual representation. Very few types (none that I can think of immediately) carry around information about a textual representation with them - so for example, a DateTime can be parsed from a variety of formats, but has no "memory" of an original text format. It's just a date and time, which could then be formatted according to any format.
If you need to maintain the idea of "a decimal number and the culture in which it was originally represented" then you should create your own class or struct for that pairing. It's not present in decimal itself.
decimal d = 0.203m;
Console.WriteLine(d.ToString(CultureInfo.InstalledUICulture));
Console.WriteLine(d.ToString(CultureInfo.InvariantCulture)); // decimal point: dot
Console.WriteLine(d.ToString(CultureInfo.GetCultureInfo("en-US"))); // default decimal point: dot
Console.WriteLine(d.ToString(CultureInfo.GetCultureInfo("ru-RU"))); // default decimal point: comma
Result:
0,203
0.203
0.203
0,203
Looks like your CurrentCulture has , as a NumberDecimalSeparator and that's why your parsing succeed.
Actually, 0.203 and 0,203 are the same as value. Only matter is their textual representation when you print it.
If you wanna get your value as a 0,203 representation, you can use a culture that has , as a NumberDecimalSeparator.
For example, my culture (tr-TR) has a ,. When you represent your decimal with it, you will get 0,203.
string myValue = "0,203";
decimal myValueAsDecimal;
decimal.TryParse(myValue, NumberStyles.Any, CultureInfo.CurrentCulture, out myValueAsDecimal);
myValueAsDecimal.ToString(new CultureInfo("tr-TR")).Dump(); // 0,203
The value of the Decimal is the same regardless of the Culture, it's
0.203
what changes is its String representation (decimal separator in your case), so
if you want to change decimal separator and don't want to change the Culture
you can just assign NumberDecimalSeparator in your custom NumberFormatInfo e.g.
Decimal d = 0.203M;
NumberFormatInfo myNumberInfo = new NumberFormatInfo() {
NumberDecimalSeparator = "," // Comma, please
};
String result = d.ToString(myNumberInfo); // "0,203"
I can not convert query string to decimal.
In this example, when I control Request.QueryString["Amount"] value, It is 32.52 After the below code works, The Amount values is 3252M like that. How can I easily do this?
decimal Amount= 0;
if (Request.QueryString["Amount"] != null)
Amount = Convert.ToDecimal(Request.QueryString["Amount"]);
Convert.ToDecimal uses your current culture settings by default.
I strongly suspect your CurrentCulture's NumberDecimalSeparator property is not ., but NumberGroupSeparator property is .
That's why your program thinks this is a thousands separator, not decimal separator and it parses as a 3252, not 32.52.
As a solution you can use a culture which have . as a NumberDecimalSeparator like InvariantCulture, or you can .Clone your current culture and set it's NumberDecimalSeparator to . 1
Amount = Convert.ToDecimal(Request.QueryString["Amount"], CultureInfo.InvariantCulture);
or
var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ".";
culture.NumberFormat.NumberGroupSeparator = ",";
Amount = Convert.ToDecimal("32.52", culture);
1: If your current culture's thousands separator is not . already. Otherwise, you need to change it as well. Both property can't have the same values for any culture
I think you are having problems with the Culture as stated in the rpevious answer. You may want to try using different cultures:
RetVal = decimal.Parse(Request.QueryString["Amount"], CultureInfo.CurrentCulture);
Then I would try:
RetVal = decimal.Parse(Request.QueryString["Amount"], CultureInfo.InvariantCulture);
I encountered an issue with C# (and Java) on the parsing/validation of culture-sensitive numerical formatting. It seems like when it comes to digit grouping, the separator can be placed anywhere in .NET. Is there a way to enforce a strict adherence of the usage of the digit grouping? For instance, see the following:
Decimal.Parse("9,0"); /// Returns 90, which is wrong
Decimal.Parse("90,00"); /// Returns 9000, which is wrong
Decimal.Parse("9,000"); /// Returns 9000, which is right
To complicate things, cultures differ in the number of digits per group.
Any suggestions?
Edit: It was suggested I add CultureInfo into the Parse(), but that does not work properly still. For instance:
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US"); /// Murican English
Double.Parse("9,0", culture); /// Returns 90 when it should throw an exception
culture = CultureInfo.CreateSpecificCulture("pt-BR"); /// Brazillian Portuguese
Double.Parse("9.0", culture); /// Returns 90 when it should throw an exception
you can find information on parsing in here as use CultureInfo culture as seen in the example in the link
for example
culture = CultureInfo.CreateSpecificCulture("en-US");
number = Double.Parse(value, culture);// 1,304.16 --> 1304.16
but "en-US" can't parse "1 304,16". "fr-FR" can --> you'll get 1304.16
You should specify CultureInfo, since parsing results are culture dependent e.g.
// English, United States:
// "," is a thousand but not decimal separator, decimal separator is "."
// d1 = 90 since "," is NOT a decimal separator
Decimal d1 = Decimal.Parse("9,0", new CultureInfo("en-US")); // <- 90
// Russian, Russia:
// "," is a decimal separator
// d2 = 9.0 since "," is a decimal separator
Decimal d2 = Decimal.Parse("9,0", new CultureInfo("ru-RU")); // <- 9.0
For correctly parsing the numbers you definetly need the Source Culture Info of the number.
Refer this
Parsing numbers from different cultures in C#
I tried the following:
string val = "0.0000e+000";
float.Parse(val);
...yet got a FormatException. So I wonder: how to parse such a value into a float/double?
You have a CultureInfo.CurrentCulture (the current culture) for which the decimal dot is different. Try parsing it with the invariant culture instead:
var x = Single.Parse("0.0000e+000", CultureInfo.InvariantCulture);
To illustrate the problem: if you were Russian, your current culture would be set to ru-RU. And then the following fails:
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo("ru-RU");
var x = Single.Parse("0.0000e+000");
FormatException: Input string was not in a correct format.
If you are French (fr-FR), it will fail too. It will probably fail for some other cultures too.
I have a double number as string. The number is
202.667,40
Which is 202667.4
How can I parse this string to get the value like: Double.Parse("202.667,40",?what here), or any other method to get the value would be great. Thanks
First, you need to know which culture this number is from, then:
CultureInfo culture = new CultureInfo("de"); // I'm assuming german here.
double number = Double.Parse("202.667,40", culture);
If you want to parse using the current thread culture, which by default is the one set for the current user:
double number = Double.Parse("202.667,40", CultureInfo.CurrentCulture);
I think i have found a solution which does not require a culture. Using a NumberFormatInfo you can force a format, no matter the culture:
// This is invariant
NumberFormatInfo format = new NumberFormatInfo();
// Set the 'splitter' for thousands
format.NumberGroupSeparator = ".";
// Set the decimal seperator
format.NumberDecimalSeparator = ",";
Then later:
System.Diagnostics.Debug.WriteLine(double.Parse("202.667,40", format)));
Outputs:
202667,4
Of course, this output (inner toString()) might differ per Culture(!)
Note that changing the input to "202,667.40" will result in a parse error, so the format should match your expected input.
Hope this helps someone..
Instead of having to specify a locale in all parses, I prefer to set an application wide locale, although if string formats are not consistent across the app, this might not work.
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("pt-PT");
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("pt-PT");
Defining this at the begining of your application will make all double parses expect a comma as the decimal delimiter.
You could use Double.Parse(your_number, CultureInfo.CurrentCulture) and set CurrentCulture accordingly with Thread.CurrentThread.CurrentCulture.
Example:
Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
then later
Double.Parse(your_number, CultureInfo.CurrentCulture);
Note that if you explicitly assign the culture to the CurrentThread, it only applies to that thread.
var val=double.Parse( yourValue, CultureInfo.InvariantCulture);
http://www.erikschierboom.com/2014/09/01/numbers-and-culture/
For more flexibility you can set NumberDecimalSeparator
string number = "202.667,40";
double.Parse(number.Replace(".", ""), new CultureInfo(CultureInfo.CurrentCulture.Name) {NumberFormat = new NumberFormatInfo() {NumberDecimalSeparator = ","}});
Double.Parse("202.667,40", new System.Globalization.CultureInfo("de-DE"));
Instead of de-DE use whatever culture the string is in.