Parsing double value for current culture - c#

ASP.NET MVC doesn't bind "1.5" double value(because invalid format for current culture). So i am trying to parse it manualy for current culture.
My solution is replacing "1.5" float point with valid float seperator for current culture.
How can i replace float seperator by valid seperator in current culture ?
Do you have better solution for it ?

Just specify which culture you want to use when parsing:
CultureInfo culture = new CultureInfo(Request.UserLanguages[0]);
return double.Parse("1.5", culture.NumberFormat);
See the documentation for more detail.

If you just want to have "1.5" parse no matter the culture, try this:
var culture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
Double.Parse("1.5", culture.NumberFormat);
That creates an instance of the en-US culture and tells the parser to use it in this specific case.

Related

Decimal.TryParse - missing separator?

I have strange situation, when I use API. I get object in JSON, which I deserialize. This object contains string property which is parsed to decimal.
To do this I use this code. I live in Poland where decimal separator is ',', so I use replace method.
string input ="160.00"; //value from API
decimal result;
decimal.TryParse(input.Replace('.',','), out result);
From time to time I result is equals 16000!! (I suppose TryParse method delete separator, it not determined).
How can I prevent this situation? Can I parse
Numbers should be serialized as InvariantCulture anyway so the InvariantCulture for parsing is a good start. The code serializing the numbers should also be checked whether it follows this rule.
string input ="160.00";
decimal result = decimal.Parse(
input,
System.Globalization.CultureInfo.InvariantCulture);
Not serializing numbers as culture invariant is one of the most common source of problems like it runs on my machine I have no idea why it doesn't on yours... oh you say your system is in a different language oops ;-)
Instead of replacing decimal point character you should be using a proper overload of TryParse method, i.e. decimal.TryParse(String, NumberStyles, IFormatProvider, Decimal):
string input ="160.00";
NumberStyles style = NumberStyles.Number;
decimal number = 0;
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
decimal.TryParse(input, style, culture, out number)
Make sure to specify the correct culture which is suitable for your case.

Parse DateTime in C#

I am trying to parse a TimeString that looks like:
11/Apr/2014:00:00:12 +0200
my code looks like
DateTime.ParseExact("11/Apr/2014:00:00:12 +0200", "dd/MMM/yyyy:HH:mm:ss zzz", null)
I looked at the MSDN and it looks good for me but I have no clue why I always get a FormatException.
You should add the InvariantCulture as a format provider.
var d = DateTime.ParseExact("11/Apr/2014:00:00:12 +0200", "dd/MMM/yyyy:HH:mm:ss zzz", CultureInfo.InvariantCulture);
Your format string is considering that the / and : characters are specific format separators that will resolve to the ones defined in your current culture, just as HH would signify "hours" in your format. Please refer to this page to see that the time separator and date separator are predefined and will be replaced by the culture specific values.
It is possible to escape the special characters but I think that in the long run your code will be much safer with the InvariantCulture

Convert object to single. CultureInfo problems

So I have the following line of code :
Single xFreq = Convert.ToSingle(param, CultureInfo.InvariantCulture);
Variable param is a System.Object Any reason the result is not the same if the "," separator is used instead of the "."? For example 0.45 is converted correctly but 0,45 is converted to 45... This thing keeps bugging me for the last hour...
Not sure what your question is since you explicitly specifying InvariantCulture for parsing the string value - hence "." is used as separator.
You need to specify CultureInfo that matches your input. Generally to parse user input you need to use current culture. If input comes from some other source you have to know what culture it was serialized with.
Because the decimal separator is Culture dependent, as other posts clarified, for InvariantCulture it's "." (CultureInfo.InvariantCulture.NumberFormat). You can look at the NumberFormatInfo article for more details regarding other separators for number types.
Invariant culture converts from and to "." like a separator. Instead the string you converting from is not in in ariant culture format, hou need specify string's culture.
Thd basic technique in this case could be to STORE in invariant culture, but show to user what he wants like a separator, so you will get rid of any culture dependent problem and user will happy to see what he likes to see.
Regards.

Formatting numbers in different cultures

Assuming an invariant culture, is it possible to define a different group separator in the format - than the comma?
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Console.WriteLine(String.Format("{0:#,##0}", 2295));
Output:
2,295
Desired output:
2.295
The invariant culture is a requirement because currencies from many different locales are being formatted with format strings, that have been user defined. Ie for Denmark they have defined the price format to be "{0:0},-", while for Ireland it might be "€{0:#,##0}".
When you have different format strings, this does not mean that you have to use InvariantCulture. If you have a format string for germany e.g. you format this string using the Culture("de-de"):
String.Format(CultureInfo.GetCultureInfo( "de-de" ), "{0:0},-", 2295) //will result in 2.295,-
String.Format(CultureInfo.GetCultureInfo( "en-us" ), "{0:0},-", 2295) //will result in 2,295,-
Alternatively you can specify your custom number format info:
NumberFormatInfo nfi = new NumberFormatInfo( )
{
CurrencyGroupSeparator = ":"
};
String.Format(nfi, "{0:0},-", 2295) //will result in 2:295,-
The normal approach would be to not use an Invariant culture.
You do specify the formatting in Invariant style, but the proper symbols would be substituted, #,##0.00 will come out as 1.234,50 or as 1,235.50 depending on the actual culture used.

Convert localized string into decimal

I have a string, that could look like "123,34", "123123,09", "1234", "123.34", "123123.09"
(Stringrepresentation of 10,2 decimal that will be stored into a MySql DB)
Due to the culture of the ASP.net thread may differ, because my application supports localization, I need to find a safe way to convert the most likely user input into a decimal.
How is that possible?
I tried various Decimal.Parse attemps, that all failed so far.
Solution:
My final solution was a mixed one. I used string replace to ensure my date is formatted into the specified CultureInfo I used for parsing
You should read current Culture Info
and than you could
//CultureInfo culture = new CultureInfo("en-US");
Convert.ToDecimal(value, System.Globalization.CultureInfo.CurrentCulture)
Decimal.Parse is the way to go but you need the particular overload that incorporates localisation, Decimal.Parse Method (String, IFormatProvider).
Once the decimal is turned into a string, there is really no foolproof way of telling which culture formatting was used to format it.
You have two options :
Record the formatting culture used and pass that back with the string, then use that for the appropriate decimal.Parse(string, IFormatProvider)
Perform the parse at the UI level (where the culture is known) and pass the value back as a decimal type.
Decimal.Parse (String, IFormatProvider)
where IFormatProvider is culture-specific format for your strings
Convert your string with the InvariantCulture
Decimal.parse(yourstring,System.Globalization.CultureInfo.InvariantCulture);
Thought you might get some weird results if your string is not compatible with the cultureinfo of the system.

Categories

Resources