1

I need to check whether figure has decimal point or not.

Example.

Figure      Result
=====================
1           false
1.0         true
0.0         true
0           false

I found different solutions for check figure value is integer or double. But i want to check figure has decimal point or not. eg. Figure is 1.0 .it should return true result.

Can you please provide me better solutions?

Tushar
  • 410
  • 4
  • 20
  • This post answers what you want - http://stackoverflow.com/questions/2751593/how-to-determine-if-a-decimal-double-is-an-integer – shekhar Oct 14 '15 at 05:46
  • Possible duplicate of [Check if a number has a decimal place/is a whole number](http://stackoverflow.com/questions/2304052/check-if-a-number-has-a-decimal-place-is-a-whole-number) – japzdivino Oct 14 '15 at 06:30

1 Answers1

4

Given the little input and assuming that what you call figure is given to you as a string, this is what comes to my mind.

var figures = new[] {"1", "1.0", "0.0", "0"};

foreach(var figure in figures) 
{
    if (figure.Contains("."))
    {
        Console.WriteLine("point");
    }
    else
    {
        Console.WriteLine("no point");
    }
}

Regex would probably be a better way to go.

foreach (var figure in figures)
{
    if (Regex.IsMatch(figure, @"^\d+\.\d+$"))
    {
        Console.WriteLine("{0}: Floatingpoint Number", figure);
    }
    else if (Regex.IsMatch(figure, @"^\d+$"))
    {
        Console.WriteLine("{0}: Integer Number", figure);
    }
    else
    {
        Console.WriteLine("{0}: No Number", figure);
    }
}

Yet again, you could use the TryParse-Methods of the types you want to check like that:

foreach (var figure in figures)
{
    int intOut;
    decimal decimalOut;

    // Note that you would have to check for integers first, because 
    // integers would otherwise be detected as valid decimals in advance.

    if (int.TryParse(figure, out intOut))
    {
        Console.WriteLine("{0}: Integer Number", figure);
    }
    else if (decimal.TryParse(figure, out decimalOut))
    {
        Console.WriteLine("{0}: Floatingpoint Number", figure);
    }
    else
    {
        Console.WriteLine("{0}: No Number", figure);
    }
}

If your figures are of type decimal, double or float, the easiest way to determine whether they would make valid integers it to do a modulo check like that:

decimal figure = 1.0m;
Console.WriteLine(figure % 1 == 0 ? "Integer Number" : "Floatingpoint Number"); // deviding by 1 leaves no remainder

You should be more specific on what your goal is, especially what type your figures are of.

nozzleman
  • 9,529
  • 4
  • 37
  • 58