1

I have a textbox where the user can enter a double point number . For eg:-

1.00
1.0000
1.23
1.000000

etc , the double numbers from the UI can be entered.

In my C# code I have to validate if the user has entered 1 or not.

1.00
1.0000
1.000000

are all considered as 1 and pass the validation . I was thinking of converting to Int

public bool Validate(double number)
{
  int v = Convert.ToInt32(number)
  if(v == 1)
   return true;
}

But the problem is I will lose precision , both 1.00 and 1.001 will result as 1 and incorrectly 1.001 will be returned as true which I dont need. How to check if the user has entered 1.00,1.000,...etc from UI in C#?

Edit : I dont need true for numbers like 1.23, 1.001 etc

VA1267
  • 311
  • 1
  • 8
  • 1
    Does this answer your question? [Floating point comparison functions for C#](https://stackoverflow.com/questions/3874627/floating-point-comparison-functions-for-c-sharp) – Markus Deibel Nov 08 '21 at 12:50
  • 4
    I must be missing something - why not just `return (number == 1)`? – Matthew Watson Nov 08 '21 at 12:58
  • Note that user can still type something like "1.0000000000000001" and it will be equal to 1 no matter what, because it will parse (with `double.Parse`) as 1 (double doesn't have precision to represent such value). – Evk Nov 08 '21 at 13:12

2 Answers2

4

Comparing the value to 1.0 should do the trick:

bool isOne = val == 1.0;

(Equality comparison of floating-point numbers can be tricky, but this one works the way you'd expect.)

Edit: Using 1 instead of 1.0 also works, as Matthew Watson suggested in the comments.

Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
2

You can use decimal data type

public bool Validate(double number)
{
    var num = decimal.Parse(number.ToString());
    if(num == 1)
        return true;
    return false;
}
Maxian Nicu
  • 2,166
  • 3
  • 17
  • 31