Kate
Kate

Reputation: 945

How do I calculate a percentage of a number in C#?

I am new to C# and I am using windows forms. I want to calculate percentage of a number by using simple math. For example:

Calculate 25% of 80.

double result` = (80 / 100) * 25

Result = 20

Another example: 25% of 30 = 7.5

However, when I tested this method of calculating the percentage, I always get zero result in MessageBox.Show()

private void button1_Click(object sender, EventArgs e)
{
    double result;             

    result = (80 / 100) * 25;
    MessageBox.Show(result.ToString());
}

The MessageBox.Show() always shows shows zero result, I tried MessageBox.Show(result.ToString("F")) and MessageBox.Show(result.ToString("0.00")) and the result still zero. I have no idea why I am getting zero. Please help me how to calculate the percentage.

Thank you

Upvotes: 8

Views: 38239

Answers (5)

Lobstergoat
Lobstergoat

Reputation: 113

I had this problem as well. I know the problem has already been solved but this is how I managed to get around it :)

int number = 80;
int percentWanted = 25;
float divideBy = 100 / percentWanted;
float percentOfNumberAsNumber = number / divideBy;

Upvotes: 1

Silthus
Silthus

Reputation: 1719

Your numbers in the calculation are of type int they need to be of type double or else the result will automatically be converted to int.

As soon as one of the inputs is of type double the result will also use that type and not drop the digits after 0.

Try this:

result = (80.0 / 100.0)* 25.0;

Upvotes: 3

Mohsen Sarkar
Mohsen Sarkar

Reputation: 6040

You have two problem in your code.
First is integer division which stated by other answers.
Second is your math logic which no one stated.

Use following code that fixes both of problems.

private void button1_Click(object sender, EventArgs e)
{
    double result;             
    result = (25f / 100f)* 80;
    MessageBox.Show(result.ToString()); //prints 20
}

Upvotes: 1

mohsen
mohsen

Reputation: 1806

Use below extension method

public static double Percent(this double number,int percent)
{
    //return ((double) 80         *       25)/100;
    return ((double)number * percent) / 100;
}

Use like this

double result = 25.0.Percent(80);

Upvotes: 1

Hari Prasad
Hari Prasad

Reputation: 16986

Problem is integer division.

Integer division results in an integer. If you want to get the results cast to respective double/float/decimal.

result = ((double) 80 / 100)* 25;

Upvotes: 19

Related Questions