Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if a string is percentage value

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@)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 %

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading