Question

Depending of browser language I am getting string like

123.22

or

123,22

So sometimes I am facing an exception here

Convert.ToDecimal(item.UnitPrice);

I would like to create some expression so the convertion should be done based on current culture. Is it possible to do?

Was it helpful?

Solution

You didn't tell us what is your CultureInfo but anyway..

Let's assume your NumberFormatInfo.NumberDecimalSeparator is , instead of .

Your string 123,22 works well like;

string s = "123,23";
decimal d = Convert.ToDecimal(s, CultureInfo.CurrentCulture); //123,23

If your string is 123.22, then you can use String.Replace method for replacing , instead of . like;

string s = "123.23";
if(s.Contains('.'))
   s = s.Replace('.', ',');
decimal d = Convert.ToDecimal(s, CultureInfo.CurrentCulture); //123,23

OTHER TIPS

Convert.ToDecimal() is already using the CultureInfo.CurrentCulture, it is just not set to the same value as the browser.

You could try specifying in the web.config file that the current culture be inherited from the browser: http://msdn.microsoft.com/en-us/library/bz9tc508.aspx

Usually a better direction would be to make sure the browser submits consistent values not depending on the browser language.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top