views:

117

answers:

2

I'm writing a banking system and my customer wants support both Russian and American numeric standards in decimal digits delimiter. Respectively . and ,.

Now only , works properly. Perhaps because of web server's OS format (Russian is set).

String like 2000.00 throws a FormatException:

Input string was not in a correct format.

How to fix that? I have next two ideas:

protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
{
   var txtAmount = (TextBox)((FormView)sender).FindControl("txtAmount"));
   txtAmount.Text = txtAmount.Text.Replace('.', ',');
}

or

protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
{
   var ru = new CultureInfo("ru-RU");
   var en = new CultureInfo("en-US")

   decimal d;
   var txtAmount = (TextBox)((FormView)sender).FindControl("txtAmount"));
   if (!Decimal.TryParse(value, NumberStyles.Any, ru, out d)
     && Decimal.TryParse(value, NumberStyles.Any, en, out d)
   {
       // data isn't in Russian format but is in American
       txtAmount.Text = d.ToString(ru);
   }
}

Are there any other ideas?

+2  A: 

You could try parse to Russian format first and (if unsuccessful) then to US:

CultureInfo ru = CultureInfo.GetCultureInfo("ru-RU");
CultureInfo us = CultureInfo.GetCultureInfo("en-US");

string value = "2000,00";
decimal result;
if (!decimal.TryParse(value, NumberStyles.Any, ru, out result))
{
    if (!decimal.TryParse(value, NumberStyles.Any, us, out result))
    {
        throw new FormatException();
    }
}

This should work for both 2000,00 and 2000.00 values.

Also, AFAIK NumberFormatInfo class doesn't accept multiple values for separators (e.g. ",." for NumberDecimalSeparator or CurrencyDecimalSeparator properties).

Suppose, String.Replace is also is not a very good idea because US culture uses comma symbol as group separator (RU uses space).

Alex
Yea, I was thinking about `Decimal.TryParse` too. But keep in mind - I'm inserting the data using `SqlDataSource` so it being parsed not by me in code-behind but by ASP.NET. So I need to prepare the data not to parse
abatishchev
A: 

How about using String.Format for currency?

Here is short example:

decimal money = 999.99m;
string html = String.Format("Total: {0:C}", money);

Information on how to use String.Format + specific culture can be found here.

Genady Sergeev
My Amount is into a `asp:TextBox` within a `asp:FormView`
abatishchev