MilkBottle
MilkBottle

Reputation: 4332

How to tell if user enter an integer or Double or Decimal

I need to find out what value the user has entered into a textbox.

The user could've entered an integer, double or decimal number into the textbox.

Which one should I use to validate the value?

Double.Parse(txtboxNo.text) 
int.Parse(txtboxNo.text);
Decimal.Parse(txtboxNo.text)

I tried this (if user enter 1 or 1.8, this function still work):

public bool IsNumeric(string strNbr)
{
    Double d_Nbr;

    try
    {
        d_Nbr = Double.Parse(strNbr);
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

My problem: I am working on a mobile Sales App. The sales man has the rights to change the price. Salesman want to work fast. So, I need to detect if he enter a correct price ( my price is decimal) what if he enter : example: 1 or 1.0 or 23 or 333.0 or press for fun 123456 . How I handle ?

Upvotes: 0

Views: 3740

Answers (3)

Ahmed Abaza
Ahmed Abaza

Reputation: 89

You may use*

double output;
if(double.tryParse(txtboxNo.Text,output))
{
 // it's double
}
else{// not double }

Upvotes: -1

Thomas
Thomas

Reputation: 2984

Differentating between an int and a double/decimal is not much of a problem you would only need to test if it has a decimal point. The problem only starts as soon as you try to differentate between double and decimal as both have decimal points and the only difference is the precision as can be seen here: Difference between decimal, float and double in .NET?

One possibility I can see is that you try to look for a decimal point and then see if it has enough digits to be seen sa decimal rather than float. String textBoxValue = txtboxNo.Text.Replace(',', '.');

if (textBoxValue.IndexOf(".") >= 0) 
{
    // double or decimal
    if (textBoxValue.length >= 17)
    {
        // Possible decimal as too long for double
        Decimal mydec;
        if (Decimal.TryParse(textBoxValue , out mydec))
        {
           // Is decimal
        }
       else
       {
           // Is something else
       }
    } 
    else
    {
       double mydoub;
       if (Double.TryParse(textBoxValue, out mydoub))
       {
           // Is double
       }
       else
       {
           // Is something else
       }
    }
}
else
{
    int myInt;
    // possible int 
    if (int.TryParse(textBoxValue, out myInt))
    { 
        // its an int
    }
    else
    {
        // something else
    }
}

Upvotes: 1

Zalem
Zalem

Reputation: 164

I'm not sure about the purpose but you may try the TryParse() Method of Double/Int/Decimal to Validate the string Value.

if (Double.TryParse(value, out number))
   Console.WriteLine(number);
else
   Console.WriteLine("{0} is outside the range of a Double.",

MSDN article: http://msdn.microsoft.com/en-us/library/994c0zb1%28v=vs.110%29.aspx

Upvotes: 1

Related Questions