c# - 尝试将数字格式化为百分比

标签 c# formatting

我想弄清楚如何将文本框中显示的数字转换为百分比。

我的程序基本上是计算 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/

相关文章:

c# - 对于随机图像,GDI+ 中发生一般错误

c# - 系统.InvalidCastException : Failed to convert parameter value from a XElement to a String

c# - 部署 NetFwTypeLib 以管理 Windows 防火墙

python - 在使用 pandas 样式创建的列中使用条形图格式从 pandas 写入 excel 文件

Vim:重新格式化和重新缩进注释的自动方式?

c# - WPF Datagrid 对具有空元素的列进行排序

c# - C#/ASP.NET 中的控制数组类型循环

python - 在 python 中格式化数字以显示

php - 文本加权到段落的最后一行

javascript - 在 AngularJS 上使用欧元符号格式化输入