I’m trying to write this in C#. The requirement is very straightforward – check if a string input is a value within the range from 0 to 100.
- I want to make sure the string is either an integer value in the range of 0 to 100 or
- a double that’s within the same range as well.
So for example, these are the accepted values:
0
50
100
0.1
50.7
100.0
I checked the double.parse method here but not sure if it’s the one I’m looking for: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-7.0#system-double-tryparse(system-string-system-iformatprovider-system-double@)
The reason is that it can also parse string like this one: 0.64e2 (which is 64)
Is this something that can be achieved with built-in library already?
>Solution :
Wrote you a little snippet:
// C# function to check if string is a percentage between 0 and 100
public static bool IsPercentage(string s)
{
double d;
if (double.TryParse(s, out d))
{
return d >= 0 && d <= 100;
}
return false;
}
Also returns false if the string contains %