我想弄清楚如何将文本框中显示的数字转换为百分比。
我的程序基本上是计算 2016 年和 2017 年售出汽车的百分比变化。
为了测试它,我做了 2016 年售出的汽车 = 7 辆和 2017 年售出的汽车 = 12 辆,我得到了一个非常长的数字。我知道您使用 (“p”) 或 (“P”) 来格式化数字,但我就是不知道该放在哪里?
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);
}
最佳答案
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
因为您在打印前计算百分比。如果你使用格式化程序那么你会得到不好的结果。您只需要一个字符串格式化程序的数字,即可将其转换为百分比。不要乘以 100 并使用格式化程序。
您实际上在 PrecentChanged
变量中有百分比。
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);
输出 71.43%
如果乘以100然后使用formatter
输出 值(value):7,142.86%。
关于c# - 尝试将数字格式化为百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48525012/