Home > Mobile >  Check if a string is percentage value
Check if a string is percentage value

Time:11-30

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.

  1. I want to make sure the string is either an integer value in the range of 0 to 100 or
  2. 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?

CodePudding user response:

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;
    // regex check if s is a string with only numbers or decimal point
    if (Regex.IsMatch(s, @"^\d \.?\d*$"))
    {
        d = Convert.ToDouble(s);
        return d >= 0 && d <= 100;
    }
    return false;
}

Also returns false if the string contains % or has exponential (e).

CodePudding user response:

if my understanding of the Q was correct and exponential representations like mentioned "0.64e2" is unwanted:

static bool IsPercentage(string s)
{

  if (Single.TryParse(s, NumberStyles.AllowLeadingSign |
        NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out Single n))
          return n >= 0 && n <= 100;

return false;

}

  •  Tags:  
  • c#
  • Related