Reputation:
I am looking for a relatively simple way to convert an integer value, which is guaranteed to be between 0 and 100, to it's decimal percentage equivalent. What I mean is if I were to have a number like 33, I would want to add a zero and a decimal place in front of it, so it would become 0.33(33%).
Here is what I have as a solution so far:
static void Main( string[] args )
{
int number = 33;
Console.WriteLine(ConvertToPercent(number));
Console.Read();
}
private static double ConvertToPercent(int value)
{
if (value >= 100)
{
return 1.0D;
}
if (value <= 0)
{
return 0.0D;
}
return Double.Parse("0." + value);
}
Is there a better, more performant way to do this using existing .NET functionality?
EDIT:
My final solution to this problem in a single method:
public static double ConvertToPercent( int value )
{
return ( double )( ( value < 0 ) ? 0 : ( value > 100 ) ? 100 : value ) / 100;
}
Upvotes: 0
Views: 84
Reputation: 71
Instead of Double.Parse
you can try just (decimal)value * 0.01m
. The rest is fine.
Upvotes: 0