tags:

views:

183

answers:

5

Hi All,

I'm sure this is a piece of cake but I'm really struggling with something that seems trivial.

I need to check the inputted text of a textbox on the form submit and check to see if it's within a desired range (I've tried a Range Validator but it doesn't work for some reason so I'm trying to do this server-side).

What I want to do is:

Get the value inputted (eg. 0.02), replace the commas and periods, convert that to a decimal (or double or equivalent) and check to see if it's between 0.10 and 35000.00.

Here's what I have so far:

string s = txtTransactionValue.Text.Replace(",", string.Empty).Replace(".", string.Empty);
        decimal transactionValue = Decimal.Parse(s);
        if (transactionValue >= 0.10M && transactionValue <= 35000.00M) // do something

If I pass 0.02 into the above, transactionValue is 2. I want to retain the value as 0.02 (ie. do no format changes to it - 100.00 is 100.00, 999.99 is 999.99)

Any ideas?

Thanks in advance, Brett

+2  A: 

You're replacing "." with nothing so your input goes from "0.02" to "002" which will parse as 2.0.

Why are you replacing the commas and periods (decimal points)?

ChrisF
+3  A: 

You are replacing any occurrences of "." or "," with String.Empty, resulting in a string with no seperators at all. Better use decimal.Parse() or decimal.TryParse() with appropiate CultureInfo and NumberStyles.

Femaref
Thanks! I was doing the replace on the string because upon submission I need to pass 199.99 as 19999 into a web service.Tanks again!
Brett
+1  A: 

You're replacing the "dot". This means that "0.02" will be "002" which will parse like "2".

Just don't replace the "dot". and i think that the replace of the comma isn't necessary eather.

bruno
A: 

As the others already mentioned you throw away the dots and commas. Maybe you're doing this, because you have some problems depending on the language the user has, cause in different cultures the dot and comma has a different meaning.

So if you know the language of the user you can try one of them:

decimal value = Decimal.Parse("0.02", CultureInfo.GetCultureInfo("en-US"));
decimal value = Decimal.Parse("0,02", CultureInfo.GetCultureInfo("de-DE"));
Oliver
+1  A: 

You can also make a simple method to take into consideration CultureInfo and NumberStyles you want. Here is my suggestion:

 public decimal ParseDecimal(string input)
{
    CultureInfo cultureInfo = null;
    NumberStyles style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
    decimal value = 0;
    string[] userLanguages = HttpContext.Current.Request.UserLanguages;
    if (userLanguages.Length > 0)
    {
        cultureInfo = new CultureInfo(userLanguages[0]);
        Decimal.TryParse(input, style, cultureInfo, out value);
    }

    return value;
}
ppolyzos