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
CodePudding user response:
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.
CodePudding user response:
You can use decimal
data type
public bool Validate(double number)
{
var num = decimal.Parse(number.ToString());
if(num == 1)
return true;
return false;
}
CodePudding user response:
You could substract the reference number and check if the result is 0.0
:
public bool Validate(double number)
{
double rest = number - 1;
return rest == 0.0;
}