1

For example in a console application I have the following code:

Console.Writeline("Enter function");
string function = Console.Readline();

and then function gets defined as:

function = "ceil(5.0)";

then I would define the variable as a double. But what if the user would enter:

function = "ceil(5)";

How can I do a check if there is a double filled in or an integer so I now how to store that variable. And also if its the same but then with negative numbers, I already tried regex but maybe I didn't do it right. Any ideas?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • 1
    Modify the code parsing the function entered by the user to detect the presence of a decimal point? Surely, if you are able to write a function parser, that should be piece of cake for you? – Heinzi Apr 26 '16 at 07:43
  • @Heinzi Thanks i will look into that, but then if there is for example 5.0 its recognized as a double but it actually is an integer if you know what i mean – Jurriaan Buitenweg Apr 26 '16 at 07:47
  • I know what you mean, but I would recommend to *still* use a double in that case: That's what most programming languages do if you use a literal such as `5.0`, and it would be confusing to change that convention. – Heinzi Apr 26 '16 at 07:55

2 Answers2

3

For floating point numbers, n % 1 == 0 is typically the way to check if there is anything past the decimal point.

public static void Main (string[] args)
{
    decimal d = 3.1M;
    Console.WriteLine((d % 1) == 0);
    d = 3.0M;
    Console.WriteLine((d % 1) == 0);
}

Output:

False //is a double
True //is a integer

More information can be found at this page: How to determine if a decimal/double is an integer?

Community
  • 1
  • 1
Robin Dirksen
  • 3,322
  • 25
  • 40
  • 1
    I think the asker wants it the other way, check if string contains double or integer. You are checking if a double is a whole number or contains decimals. – RvdK Apr 26 '16 at 07:43
0

If you want to do it using Regex, you could check for function+parenthesis+value+closing_parenthesis. Check this as a starting point:

ceil\((\-?\d{1,}(?:.\d{1,})?)\)

Please note that Regex allows negative numbers. If you don't want that, remove the \-? part.

Cleptus
  • 3,446
  • 4
  • 28
  • 34