Decimal positions as a result of C #

I have this code that computes a summary of 2 multiplied columns of all rows in a datagridview.

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()); } } 

How can I improve decimal positions? Now the result looks like this: 123.5484250 I would like to have only 2 decimal positions with the result, for example, 123.55.

Sorry for my poor english. I hope the “decimal position” is the expression for the word that I really mean. In case I made an example for a better understanding.

Thank you all for your time, comments and answers.

+4
source share
4 answers

Use the format string to convert text:

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

For more information on formatting numbers, see this list . You can also use

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

which is exactly the same as the code above.

+2
source

Since you are using a DataGridView , you can set the cell format, e.g.

 DataGridView1.Columns[required column index or name].DefaultCellStyle.Format = "N2" 
+4
source

You can use Math.Round(value, digits)

The value is your result, and the numbers are how many decimal digits you want

+2
source

Use System.Globalization.NumberFormatInfo to manage settings.

 System.Globalization.NumberFormatInfo numberFormatInfo = new System.Globalization.NumberFormatInfo(); numberFormatInfo.NumberDecimalDigits = 2; decimal decimalexample = 123.5484250M; string decimalasstring = decimalexample.ToString(numberFormatInfo); 

Sincerely.

+1
source

Source: https://habr.com/ru/post/1494452/


All Articles