calculating a percentage from a value C#

时间:2016-04-21 22:05:12

标签: c#

I'm trying to output a percentage from a value imputed from a textbox. Here is my code;

int firstNumber;
double mydouble1 = 0.15;
int myint1 = (int)mydouble1;

int.TryParse(HouseValue.Text, out firstNumber);

int answer;
answer = (firstNumber) * (myint1);
prem1.Text = answer.ToString();

The problem is when I run the app and enter a value to calculate, the answer is 0. I cant seem to get it to display the correct amount for 0.15% of the value.

3 个答案:

答案 0 :(得分:0)

Try this: change your answer from an int to a double:

int firstNumber;
double mydouble1 = 0.15;

if (int.TryParse(HouseValue.Text, out firstNumber))
{
    double answer = firstNumber * mydouble1;
    prem1.Text = answer.ToString(); // you may want to round/format this
}

答案 1 :(得分:0)

The problem is that casting 0.15 to int makes it 0

(int)0.15 == 0

The double type has primarily been made for scientific calculations. You should use decimal when dealing with money, since decimal fractions can often not be translated into binary numbers (used internally to store doubles) without loss of precision.

    decimal percentage = 0.15m;
    int houseValue;
    if (Int32.TryParse(HouseValue.Text, out houseValue)) {
        decimal result = Math.Round(percentage * houseValue);
        prem1.Text = result.ToString();
    } else {
        prem1.Text = "Please enter valid house value!";
    }

firstNumber, myint1 and mydouble1 are terrible names. Use speaking names!

答案 2 :(得分:0)

Except error handling in converting string to int, use following code:

double mydouble1 = 0.15;
double percentage = int.Parse(ouseValue.Text) * mydouble1;