GeauxTigers
GeauxTigers

Reputation: 35

Trying to format a number to a percentage

I am trying to figure out how to convert the number that is displayed in the textbox as a percentage.

My program is basically calculating the percent change for cars sold in 2016 and 2017.

To test it out I did cars sold in 2016 = 7 and cars sold in 2017 = 12 and I got a really long number. I know that you use (“p”) or (“P”) to format the number but I just can’t figure out where to put it?

private void calcbtn_Click(object sender, EventArgs e)
{
    double carsIn2016; //  number of cars sold in 2016
    double carsIn2017; // number of cars sold in 2017
    double Percentchanged; // calculate the % change

    carsIn2016 = double.Parse(soldIn2016txtbox.Text); //get input from text box
    carsIn2017 = double.Parse(soldIn2017txtbox.Text);  // get input from text box 
    Percentchanged =(carsIn2017 - carsIn2016) / (carsIn2016 * 100); // calculate the % change 

    MessageBox.Show( "Your total % change is   " + Percentchanged);
}

Upvotes: 3

Views: 440

Answers (2)

SSD
SSD

Reputation: 1391

Precentage Difference: Work out the difference (increase) between the two numbers you are comparing. Then: divide the increase by the original number and multiply the answer by 100

Since you are calculating precent before printing. If you use formatter then you will get bad result. You just need a number for string formatter, to convert it to precent. Dont multiply by 100 and use formatter.

You actually have the precent in PrecentChanged variable.

double carsIn2016; //  number of cars sold in 2016
double carsIn2017; // number of cars sold in 2017
double Percentchanged; // calculate the % change

carsIn2016 = double.Parse("7"); //get input from text box
carsIn2017 = double.Parse("12");  // get input from text box 
Percentchanged =((carsIn2017 - carsIn2016) / (carsIn2016));//* 100); // calculate the % change 



var output = String.Format("Your total % change is : {0:P}.", Percentchanged);

Output 71.43%

If you multiply by 100 and then use formatter

Output Value: 7,142.86%.

Upvotes: 2

oppassum
oppassum

Reputation: 1765

What you're looking for is ToString(), which can be used with the "P" that you indicate.

MessageBox.Show("Your total % change is " + PercentChanged.ToString("P"));

You can also do various other formatting via ToString, as indicated on Microsoft's Website

Upvotes: 1

Related Questions