2013-07-31 66 views
4

我已经得到了这个代码,它计算了datagridview中所有行的2个乘积列的总结。结果c中的小数位#

private void vypocti_odvody(int price, int vat, int tot_rows2) 
    { 
     try 
     { 
      double outVal = 0; 
      foreach (DataGridViewRow row in dataGridView1.Rows) 

      { 
       outVal = outVal + (Convert.ToDouble(row.Cells[price].Value)/100) * Convert.ToDouble(row.Cells[vat].Value) + (Convert.ToDouble(row.Cells[price].Value)); 
      } 

     // s_ub_celk.Text = (((a/100) * b) + a).ToString(); 
      Convert.ToDecimal (result.Text = outVal.ToString()) ; 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("Chybové hlášení K3 " + ex.Message.ToString()); 
     } 


    } 

如何提高小数位数?现在结果是这样的:123,5484250我想只有2个小数位,结果例如123,55。

对不起,我可怜的英语我希望'小数位'是表达我真正的意思。如果我为了更好的理解做了一个例子。

谢谢大家的时间,评论和答案。

+0

通常有一个'Format'属性可以设置为'0.00'。 – Joey

回答

2

使用格式字符串将文本转换:

result.Text = outVal.ToString("0.00"); 

有关如何格式化数字更多的方式请参见this list。您也可以使用

result.Text = string.Format("{0:0.00}", outVal); 

这与上面的代码完全相同。

+0

为什么使用double格式的字符串格式以及何时知道string.format被截断了数字。 – 3wic

+0

@ 3wic:“0.00”会将数字四舍五入到小数点后第二位。在你的解决方案中,你可能会因为浮点错误而得到不同的结果,而'string.Format'对字符串表示本身起作用,而不是数字。 – pascalhein

+0

@ 3wic:请参阅[这个ideone](http://ideone.com/YzGX2z)OP的例子舍入。 – pascalhein

2

您可以使用Math.Round(value, digits)

的价值是你的结果和数字是多少小数想

4

由于您使用DataGridView可以设置单元格的格式一样

DataGridView1.Columns[required column index or name].DefaultCellStyle.Format = "N2" 
1

使用System.Globalization.NumberFormatInfo来控制设置。

System.Globalization.NumberFormatInfo numberFormatInfo = new System.Globalization.NumberFormatInfo();   
numberFormatInfo.NumberDecimalDigits = 2; 

decimal decimalexample = 123.5484250M; 

string decimalasstring = decimalexample.ToString(numberFormatInfo); 

问候。